OSDN Git Service

KVM: x86: change kvm_mmu_page_get_gfn BUG_ON to WARN_ON
[tomoyo/tomoyo-test1.git] / arch / x86 / kvm / mmu.c
1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * This module enables machines with Intel VT-x extensions to run virtual
5  * machines without emulation or binary translation.
6  *
7  * MMU support
8  *
9  * Copyright (C) 2006 Qumranet, Inc.
10  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
11  *
12  * Authors:
13  *   Yaniv Kamay  <yaniv@qumranet.com>
14  *   Avi Kivity   <avi@qumranet.com>
15  *
16  * This work is licensed under the terms of the GNU GPL, version 2.  See
17  * the COPYING file in the top-level directory.
18  *
19  */
20
21 #include "irq.h"
22 #include "mmu.h"
23 #include "x86.h"
24 #include "kvm_cache_regs.h"
25 #include "cpuid.h"
26
27 #include <linux/kvm_host.h>
28 #include <linux/types.h>
29 #include <linux/string.h>
30 #include <linux/mm.h>
31 #include <linux/highmem.h>
32 #include <linux/moduleparam.h>
33 #include <linux/export.h>
34 #include <linux/swap.h>
35 #include <linux/hugetlb.h>
36 #include <linux/compiler.h>
37 #include <linux/srcu.h>
38 #include <linux/slab.h>
39 #include <linux/sched/signal.h>
40 #include <linux/uaccess.h>
41 #include <linux/hash.h>
42 #include <linux/kern_levels.h>
43
44 #include <asm/page.h>
45 #include <asm/pat.h>
46 #include <asm/cmpxchg.h>
47 #include <asm/e820/api.h>
48 #include <asm/io.h>
49 #include <asm/vmx.h>
50 #include <asm/kvm_page_track.h>
51 #include "trace.h"
52
53 /*
54  * When setting this variable to true it enables Two-Dimensional-Paging
55  * where the hardware walks 2 page tables:
56  * 1. the guest-virtual to guest-physical
57  * 2. while doing 1. it walks guest-physical to host-physical
58  * If the hardware supports that we don't need to do shadow paging.
59  */
60 bool tdp_enabled = false;
61
62 enum {
63         AUDIT_PRE_PAGE_FAULT,
64         AUDIT_POST_PAGE_FAULT,
65         AUDIT_PRE_PTE_WRITE,
66         AUDIT_POST_PTE_WRITE,
67         AUDIT_PRE_SYNC,
68         AUDIT_POST_SYNC
69 };
70
71 #undef MMU_DEBUG
72
73 #ifdef MMU_DEBUG
74 static bool dbg = 0;
75 module_param(dbg, bool, 0644);
76
77 #define pgprintk(x...) do { if (dbg) printk(x); } while (0)
78 #define rmap_printk(x...) do { if (dbg) printk(x); } while (0)
79 #define MMU_WARN_ON(x) WARN_ON(x)
80 #else
81 #define pgprintk(x...) do { } while (0)
82 #define rmap_printk(x...) do { } while (0)
83 #define MMU_WARN_ON(x) do { } while (0)
84 #endif
85
86 #define PTE_PREFETCH_NUM                8
87
88 #define PT_FIRST_AVAIL_BITS_SHIFT 10
89 #define PT64_SECOND_AVAIL_BITS_SHIFT 52
90
91 #define PT64_LEVEL_BITS 9
92
93 #define PT64_LEVEL_SHIFT(level) \
94                 (PAGE_SHIFT + (level - 1) * PT64_LEVEL_BITS)
95
96 #define PT64_INDEX(address, level)\
97         (((address) >> PT64_LEVEL_SHIFT(level)) & ((1 << PT64_LEVEL_BITS) - 1))
98
99
100 #define PT32_LEVEL_BITS 10
101
102 #define PT32_LEVEL_SHIFT(level) \
103                 (PAGE_SHIFT + (level - 1) * PT32_LEVEL_BITS)
104
105 #define PT32_LVL_OFFSET_MASK(level) \
106         (PT32_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
107                                                 * PT32_LEVEL_BITS))) - 1))
108
109 #define PT32_INDEX(address, level)\
110         (((address) >> PT32_LEVEL_SHIFT(level)) & ((1 << PT32_LEVEL_BITS) - 1))
111
112
113 #ifdef CONFIG_DYNAMIC_PHYSICAL_MASK
114 #define PT64_BASE_ADDR_MASK (physical_mask & ~(u64)(PAGE_SIZE-1))
115 #else
116 #define PT64_BASE_ADDR_MASK (((1ULL << 52) - 1) & ~(u64)(PAGE_SIZE-1))
117 #endif
118 #define PT64_LVL_ADDR_MASK(level) \
119         (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
120                                                 * PT64_LEVEL_BITS))) - 1))
121 #define PT64_LVL_OFFSET_MASK(level) \
122         (PT64_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
123                                                 * PT64_LEVEL_BITS))) - 1))
124
125 #define PT32_BASE_ADDR_MASK PAGE_MASK
126 #define PT32_DIR_BASE_ADDR_MASK \
127         (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + PT32_LEVEL_BITS)) - 1))
128 #define PT32_LVL_ADDR_MASK(level) \
129         (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
130                                             * PT32_LEVEL_BITS))) - 1))
131
132 #define PT64_PERM_MASK (PT_PRESENT_MASK | PT_WRITABLE_MASK | shadow_user_mask \
133                         | shadow_x_mask | shadow_nx_mask | shadow_me_mask)
134
135 #define ACC_EXEC_MASK    1
136 #define ACC_WRITE_MASK   PT_WRITABLE_MASK
137 #define ACC_USER_MASK    PT_USER_MASK
138 #define ACC_ALL          (ACC_EXEC_MASK | ACC_WRITE_MASK | ACC_USER_MASK)
139
140 /* The mask for the R/X bits in EPT PTEs */
141 #define PT64_EPT_READABLE_MASK                  0x1ull
142 #define PT64_EPT_EXECUTABLE_MASK                0x4ull
143
144 #include <trace/events/kvm.h>
145
146 #define CREATE_TRACE_POINTS
147 #include "mmutrace.h"
148
149 #define SPTE_HOST_WRITEABLE     (1ULL << PT_FIRST_AVAIL_BITS_SHIFT)
150 #define SPTE_MMU_WRITEABLE      (1ULL << (PT_FIRST_AVAIL_BITS_SHIFT + 1))
151
152 #define SHADOW_PT_INDEX(addr, level) PT64_INDEX(addr, level)
153
154 /* make pte_list_desc fit well in cache line */
155 #define PTE_LIST_EXT 3
156
157 /*
158  * Return values of handle_mmio_page_fault and mmu.page_fault:
159  * RET_PF_RETRY: let CPU fault again on the address.
160  * RET_PF_EMULATE: mmio page fault, emulate the instruction directly.
161  *
162  * For handle_mmio_page_fault only:
163  * RET_PF_INVALID: the spte is invalid, let the real page fault path update it.
164  */
165 enum {
166         RET_PF_RETRY = 0,
167         RET_PF_EMULATE = 1,
168         RET_PF_INVALID = 2,
169 };
170
171 struct pte_list_desc {
172         u64 *sptes[PTE_LIST_EXT];
173         struct pte_list_desc *more;
174 };
175
176 struct kvm_shadow_walk_iterator {
177         u64 addr;
178         hpa_t shadow_addr;
179         u64 *sptep;
180         int level;
181         unsigned index;
182 };
183
184 static const union kvm_mmu_page_role mmu_base_role_mask = {
185         .cr0_wp = 1,
186         .gpte_is_8_bytes = 1,
187         .nxe = 1,
188         .smep_andnot_wp = 1,
189         .smap_andnot_wp = 1,
190         .smm = 1,
191         .guest_mode = 1,
192         .ad_disabled = 1,
193 };
194
195 #define for_each_shadow_entry_using_root(_vcpu, _root, _addr, _walker)     \
196         for (shadow_walk_init_using_root(&(_walker), (_vcpu),              \
197                                          (_root), (_addr));                \
198              shadow_walk_okay(&(_walker));                                 \
199              shadow_walk_next(&(_walker)))
200
201 #define for_each_shadow_entry(_vcpu, _addr, _walker)            \
202         for (shadow_walk_init(&(_walker), _vcpu, _addr);        \
203              shadow_walk_okay(&(_walker));                      \
204              shadow_walk_next(&(_walker)))
205
206 #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte)     \
207         for (shadow_walk_init(&(_walker), _vcpu, _addr);                \
208              shadow_walk_okay(&(_walker)) &&                            \
209                 ({ spte = mmu_spte_get_lockless(_walker.sptep); 1; });  \
210              __shadow_walk_next(&(_walker), spte))
211
212 static struct kmem_cache *pte_list_desc_cache;
213 static struct kmem_cache *mmu_page_header_cache;
214 static struct percpu_counter kvm_total_used_mmu_pages;
215
216 static u64 __read_mostly shadow_nx_mask;
217 static u64 __read_mostly shadow_x_mask; /* mutual exclusive with nx_mask */
218 static u64 __read_mostly shadow_user_mask;
219 static u64 __read_mostly shadow_accessed_mask;
220 static u64 __read_mostly shadow_dirty_mask;
221 static u64 __read_mostly shadow_mmio_mask;
222 static u64 __read_mostly shadow_mmio_value;
223 static u64 __read_mostly shadow_present_mask;
224 static u64 __read_mostly shadow_me_mask;
225
226 /*
227  * SPTEs used by MMUs without A/D bits are marked with shadow_acc_track_value.
228  * Non-present SPTEs with shadow_acc_track_value set are in place for access
229  * tracking.
230  */
231 static u64 __read_mostly shadow_acc_track_mask;
232 static const u64 shadow_acc_track_value = SPTE_SPECIAL_MASK;
233
234 /*
235  * The mask/shift to use for saving the original R/X bits when marking the PTE
236  * as not-present for access tracking purposes. We do not save the W bit as the
237  * PTEs being access tracked also need to be dirty tracked, so the W bit will be
238  * restored only when a write is attempted to the page.
239  */
240 static const u64 shadow_acc_track_saved_bits_mask = PT64_EPT_READABLE_MASK |
241                                                     PT64_EPT_EXECUTABLE_MASK;
242 static const u64 shadow_acc_track_saved_bits_shift = PT64_SECOND_AVAIL_BITS_SHIFT;
243
244 /*
245  * This mask must be set on all non-zero Non-Present or Reserved SPTEs in order
246  * to guard against L1TF attacks.
247  */
248 static u64 __read_mostly shadow_nonpresent_or_rsvd_mask;
249
250 /*
251  * The number of high-order 1 bits to use in the mask above.
252  */
253 static const u64 shadow_nonpresent_or_rsvd_mask_len = 5;
254
255 /*
256  * In some cases, we need to preserve the GFN of a non-present or reserved
257  * SPTE when we usurp the upper five bits of the physical address space to
258  * defend against L1TF, e.g. for MMIO SPTEs.  To preserve the GFN, we'll
259  * shift bits of the GFN that overlap with shadow_nonpresent_or_rsvd_mask
260  * left into the reserved bits, i.e. the GFN in the SPTE will be split into
261  * high and low parts.  This mask covers the lower bits of the GFN.
262  */
263 static u64 __read_mostly shadow_nonpresent_or_rsvd_lower_gfn_mask;
264
265 /*
266  * The number of non-reserved physical address bits irrespective of features
267  * that repurpose legal bits, e.g. MKTME.
268  */
269 static u8 __read_mostly shadow_phys_bits;
270
271 static void mmu_spte_set(u64 *sptep, u64 spte);
272 static union kvm_mmu_page_role
273 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu);
274
275
276 static inline bool kvm_available_flush_tlb_with_range(void)
277 {
278         return kvm_x86_ops->tlb_remote_flush_with_range;
279 }
280
281 static void kvm_flush_remote_tlbs_with_range(struct kvm *kvm,
282                 struct kvm_tlb_range *range)
283 {
284         int ret = -ENOTSUPP;
285
286         if (range && kvm_x86_ops->tlb_remote_flush_with_range)
287                 ret = kvm_x86_ops->tlb_remote_flush_with_range(kvm, range);
288
289         if (ret)
290                 kvm_flush_remote_tlbs(kvm);
291 }
292
293 static void kvm_flush_remote_tlbs_with_address(struct kvm *kvm,
294                 u64 start_gfn, u64 pages)
295 {
296         struct kvm_tlb_range range;
297
298         range.start_gfn = start_gfn;
299         range.pages = pages;
300
301         kvm_flush_remote_tlbs_with_range(kvm, &range);
302 }
303
304 void kvm_mmu_set_mmio_spte_mask(u64 mmio_mask, u64 mmio_value)
305 {
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 }
310 EXPORT_SYMBOL_GPL(kvm_mmu_set_mmio_spte_mask);
311
312 static inline bool sp_ad_disabled(struct kvm_mmu_page *sp)
313 {
314         return sp->role.ad_disabled;
315 }
316
317 static inline bool spte_ad_enabled(u64 spte)
318 {
319         MMU_WARN_ON((spte & shadow_mmio_mask) == shadow_mmio_value);
320         return !(spte & shadow_acc_track_value);
321 }
322
323 static inline u64 spte_shadow_accessed_mask(u64 spte)
324 {
325         MMU_WARN_ON((spte & shadow_mmio_mask) == shadow_mmio_value);
326         return spte_ad_enabled(spte) ? shadow_accessed_mask : 0;
327 }
328
329 static inline u64 spte_shadow_dirty_mask(u64 spte)
330 {
331         MMU_WARN_ON((spte & shadow_mmio_mask) == shadow_mmio_value);
332         return spte_ad_enabled(spte) ? shadow_dirty_mask : 0;
333 }
334
335 static inline bool is_access_track_spte(u64 spte)
336 {
337         return !spte_ad_enabled(spte) && (spte & shadow_acc_track_mask) == 0;
338 }
339
340 /*
341  * Due to limited space in PTEs, the MMIO generation is a 19 bit subset of
342  * the memslots generation and is derived as follows:
343  *
344  * Bits 0-8 of the MMIO generation are propagated to spte bits 3-11
345  * Bits 9-18 of the MMIO generation are propagated to spte bits 52-61
346  *
347  * The KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS flag is intentionally not included in
348  * the MMIO generation number, as doing so would require stealing a bit from
349  * the "real" generation number and thus effectively halve the maximum number
350  * of MMIO generations that can be handled before encountering a wrap (which
351  * requires a full MMU zap).  The flag is instead explicitly queried when
352  * checking for MMIO spte cache hits.
353  */
354 #define MMIO_SPTE_GEN_MASK              GENMASK_ULL(18, 0)
355
356 #define MMIO_SPTE_GEN_LOW_START         3
357 #define MMIO_SPTE_GEN_LOW_END           11
358 #define MMIO_SPTE_GEN_LOW_MASK          GENMASK_ULL(MMIO_SPTE_GEN_LOW_END, \
359                                                     MMIO_SPTE_GEN_LOW_START)
360
361 #define MMIO_SPTE_GEN_HIGH_START        52
362 #define MMIO_SPTE_GEN_HIGH_END          61
363 #define MMIO_SPTE_GEN_HIGH_MASK         GENMASK_ULL(MMIO_SPTE_GEN_HIGH_END, \
364                                                     MMIO_SPTE_GEN_HIGH_START)
365 static u64 generation_mmio_spte_mask(u64 gen)
366 {
367         u64 mask;
368
369         WARN_ON(gen & ~MMIO_SPTE_GEN_MASK);
370
371         mask = (gen << MMIO_SPTE_GEN_LOW_START) & MMIO_SPTE_GEN_LOW_MASK;
372         mask |= (gen << MMIO_SPTE_GEN_HIGH_START) & MMIO_SPTE_GEN_HIGH_MASK;
373         return mask;
374 }
375
376 static u64 get_mmio_spte_generation(u64 spte)
377 {
378         u64 gen;
379
380         spte &= ~shadow_mmio_mask;
381
382         gen = (spte & MMIO_SPTE_GEN_LOW_MASK) >> MMIO_SPTE_GEN_LOW_START;
383         gen |= (spte & MMIO_SPTE_GEN_HIGH_MASK) >> MMIO_SPTE_GEN_HIGH_START;
384         return gen;
385 }
386
387 static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
388                            unsigned access)
389 {
390         u64 gen = kvm_vcpu_memslots(vcpu)->generation & MMIO_SPTE_GEN_MASK;
391         u64 mask = generation_mmio_spte_mask(gen);
392         u64 gpa = gfn << PAGE_SHIFT;
393
394         access &= ACC_WRITE_MASK | ACC_USER_MASK;
395         mask |= shadow_mmio_value | access;
396         mask |= gpa | shadow_nonpresent_or_rsvd_mask;
397         mask |= (gpa & shadow_nonpresent_or_rsvd_mask)
398                 << shadow_nonpresent_or_rsvd_mask_len;
399
400         page_header(__pa(sptep))->mmio_cached = true;
401
402         trace_mark_mmio_spte(sptep, gfn, access, gen);
403         mmu_spte_set(sptep, mask);
404 }
405
406 static bool is_mmio_spte(u64 spte)
407 {
408         return (spte & shadow_mmio_mask) == shadow_mmio_value;
409 }
410
411 static gfn_t get_mmio_spte_gfn(u64 spte)
412 {
413         u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
414
415         gpa |= (spte >> shadow_nonpresent_or_rsvd_mask_len)
416                & shadow_nonpresent_or_rsvd_mask;
417
418         return gpa >> PAGE_SHIFT;
419 }
420
421 static unsigned get_mmio_spte_access(u64 spte)
422 {
423         u64 mask = generation_mmio_spte_mask(MMIO_SPTE_GEN_MASK) | shadow_mmio_mask;
424         return (spte & ~mask) & ~PAGE_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(arch/x86/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         list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
2101         kvm_mod_used_mmu_pages(vcpu->kvm, +1);
2102         return sp;
2103 }
2104
2105 static void mark_unsync(u64 *spte);
2106 static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
2107 {
2108         u64 *sptep;
2109         struct rmap_iterator iter;
2110
2111         for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
2112                 mark_unsync(sptep);
2113         }
2114 }
2115
2116 static void mark_unsync(u64 *spte)
2117 {
2118         struct kvm_mmu_page *sp;
2119         unsigned int index;
2120
2121         sp = page_header(__pa(spte));
2122         index = spte - sp->spt;
2123         if (__test_and_set_bit(index, sp->unsync_child_bitmap))
2124                 return;
2125         if (sp->unsync_children++)
2126                 return;
2127         kvm_mmu_mark_parents_unsync(sp);
2128 }
2129
2130 static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
2131                                struct kvm_mmu_page *sp)
2132 {
2133         return 0;
2134 }
2135
2136 static void nonpaging_invlpg(struct kvm_vcpu *vcpu, gva_t gva, hpa_t root)
2137 {
2138 }
2139
2140 static void nonpaging_update_pte(struct kvm_vcpu *vcpu,
2141                                  struct kvm_mmu_page *sp, u64 *spte,
2142                                  const void *pte)
2143 {
2144         WARN_ON(1);
2145 }
2146
2147 #define KVM_PAGE_ARRAY_NR 16
2148
2149 struct kvm_mmu_pages {
2150         struct mmu_page_and_offset {
2151                 struct kvm_mmu_page *sp;
2152                 unsigned int idx;
2153         } page[KVM_PAGE_ARRAY_NR];
2154         unsigned int nr;
2155 };
2156
2157 static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
2158                          int idx)
2159 {
2160         int i;
2161
2162         if (sp->unsync)
2163                 for (i=0; i < pvec->nr; i++)
2164                         if (pvec->page[i].sp == sp)
2165                                 return 0;
2166
2167         pvec->page[pvec->nr].sp = sp;
2168         pvec->page[pvec->nr].idx = idx;
2169         pvec->nr++;
2170         return (pvec->nr == KVM_PAGE_ARRAY_NR);
2171 }
2172
2173 static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
2174 {
2175         --sp->unsync_children;
2176         WARN_ON((int)sp->unsync_children < 0);
2177         __clear_bit(idx, sp->unsync_child_bitmap);
2178 }
2179
2180 static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
2181                            struct kvm_mmu_pages *pvec)
2182 {
2183         int i, ret, nr_unsync_leaf = 0;
2184
2185         for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
2186                 struct kvm_mmu_page *child;
2187                 u64 ent = sp->spt[i];
2188
2189                 if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
2190                         clear_unsync_child_bit(sp, i);
2191                         continue;
2192                 }
2193
2194                 child = page_header(ent & PT64_BASE_ADDR_MASK);
2195
2196                 if (child->unsync_children) {
2197                         if (mmu_pages_add(pvec, child, i))
2198                                 return -ENOSPC;
2199
2200                         ret = __mmu_unsync_walk(child, pvec);
2201                         if (!ret) {
2202                                 clear_unsync_child_bit(sp, i);
2203                                 continue;
2204                         } else if (ret > 0) {
2205                                 nr_unsync_leaf += ret;
2206                         } else
2207                                 return ret;
2208                 } else if (child->unsync) {
2209                         nr_unsync_leaf++;
2210                         if (mmu_pages_add(pvec, child, i))
2211                                 return -ENOSPC;
2212                 } else
2213                         clear_unsync_child_bit(sp, i);
2214         }
2215
2216         return nr_unsync_leaf;
2217 }
2218
2219 #define INVALID_INDEX (-1)
2220
2221 static int mmu_unsync_walk(struct kvm_mmu_page *sp,
2222                            struct kvm_mmu_pages *pvec)
2223 {
2224         pvec->nr = 0;
2225         if (!sp->unsync_children)
2226                 return 0;
2227
2228         mmu_pages_add(pvec, sp, INVALID_INDEX);
2229         return __mmu_unsync_walk(sp, pvec);
2230 }
2231
2232 static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2233 {
2234         WARN_ON(!sp->unsync);
2235         trace_kvm_mmu_sync_page(sp);
2236         sp->unsync = 0;
2237         --kvm->stat.mmu_unsync;
2238 }
2239
2240 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2241                                      struct list_head *invalid_list);
2242 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2243                                     struct list_head *invalid_list);
2244
2245
2246 #define for_each_valid_sp(_kvm, _sp, _gfn)                              \
2247         hlist_for_each_entry(_sp,                                       \
2248           &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)], hash_link) \
2249                 if ((_sp)->role.invalid) {    \
2250                 } else
2251
2252 #define for_each_gfn_indirect_valid_sp(_kvm, _sp, _gfn)                 \
2253         for_each_valid_sp(_kvm, _sp, _gfn)                              \
2254                 if ((_sp)->gfn != (_gfn) || (_sp)->role.direct) {} else
2255
2256 static inline bool is_ept_sp(struct kvm_mmu_page *sp)
2257 {
2258         return sp->role.cr0_wp && sp->role.smap_andnot_wp;
2259 }
2260
2261 /* @sp->gfn should be write-protected at the call site */
2262 static bool __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2263                             struct list_head *invalid_list)
2264 {
2265         if ((!is_ept_sp(sp) && sp->role.gpte_is_8_bytes != !!is_pae(vcpu)) ||
2266             vcpu->arch.mmu->sync_page(vcpu, sp) == 0) {
2267                 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
2268                 return false;
2269         }
2270
2271         return true;
2272 }
2273
2274 static bool kvm_mmu_remote_flush_or_zap(struct kvm *kvm,
2275                                         struct list_head *invalid_list,
2276                                         bool remote_flush)
2277 {
2278         if (!remote_flush && list_empty(invalid_list))
2279                 return false;
2280
2281         if (!list_empty(invalid_list))
2282                 kvm_mmu_commit_zap_page(kvm, invalid_list);
2283         else
2284                 kvm_flush_remote_tlbs(kvm);
2285         return true;
2286 }
2287
2288 static void kvm_mmu_flush_or_zap(struct kvm_vcpu *vcpu,
2289                                  struct list_head *invalid_list,
2290                                  bool remote_flush, bool local_flush)
2291 {
2292         if (kvm_mmu_remote_flush_or_zap(vcpu->kvm, invalid_list, remote_flush))
2293                 return;
2294
2295         if (local_flush)
2296                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2297 }
2298
2299 #ifdef CONFIG_KVM_MMU_AUDIT
2300 #include "mmu_audit.c"
2301 #else
2302 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, int point) { }
2303 static void mmu_audit_disable(void) { }
2304 #endif
2305
2306 static bool kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2307                          struct list_head *invalid_list)
2308 {
2309         kvm_unlink_unsync_page(vcpu->kvm, sp);
2310         return __kvm_sync_page(vcpu, sp, invalid_list);
2311 }
2312
2313 /* @gfn should be write-protected at the call site */
2314 static bool kvm_sync_pages(struct kvm_vcpu *vcpu, gfn_t gfn,
2315                            struct list_head *invalid_list)
2316 {
2317         struct kvm_mmu_page *s;
2318         bool ret = false;
2319
2320         for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
2321                 if (!s->unsync)
2322                         continue;
2323
2324                 WARN_ON(s->role.level != PT_PAGE_TABLE_LEVEL);
2325                 ret |= kvm_sync_page(vcpu, s, invalid_list);
2326         }
2327
2328         return ret;
2329 }
2330
2331 struct mmu_page_path {
2332         struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
2333         unsigned int idx[PT64_ROOT_MAX_LEVEL];
2334 };
2335
2336 #define for_each_sp(pvec, sp, parents, i)                       \
2337                 for (i = mmu_pages_first(&pvec, &parents);      \
2338                         i < pvec.nr && ({ sp = pvec.page[i].sp; 1;});   \
2339                         i = mmu_pages_next(&pvec, &parents, i))
2340
2341 static int mmu_pages_next(struct kvm_mmu_pages *pvec,
2342                           struct mmu_page_path *parents,
2343                           int i)
2344 {
2345         int n;
2346
2347         for (n = i+1; n < pvec->nr; n++) {
2348                 struct kvm_mmu_page *sp = pvec->page[n].sp;
2349                 unsigned idx = pvec->page[n].idx;
2350                 int level = sp->role.level;
2351
2352                 parents->idx[level-1] = idx;
2353                 if (level == PT_PAGE_TABLE_LEVEL)
2354                         break;
2355
2356                 parents->parent[level-2] = sp;
2357         }
2358
2359         return n;
2360 }
2361
2362 static int mmu_pages_first(struct kvm_mmu_pages *pvec,
2363                            struct mmu_page_path *parents)
2364 {
2365         struct kvm_mmu_page *sp;
2366         int level;
2367
2368         if (pvec->nr == 0)
2369                 return 0;
2370
2371         WARN_ON(pvec->page[0].idx != INVALID_INDEX);
2372
2373         sp = pvec->page[0].sp;
2374         level = sp->role.level;
2375         WARN_ON(level == PT_PAGE_TABLE_LEVEL);
2376
2377         parents->parent[level-2] = sp;
2378
2379         /* Also set up a sentinel.  Further entries in pvec are all
2380          * children of sp, so this element is never overwritten.
2381          */
2382         parents->parent[level-1] = NULL;
2383         return mmu_pages_next(pvec, parents, 0);
2384 }
2385
2386 static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2387 {
2388         struct kvm_mmu_page *sp;
2389         unsigned int level = 0;
2390
2391         do {
2392                 unsigned int idx = parents->idx[level];
2393                 sp = parents->parent[level];
2394                 if (!sp)
2395                         return;
2396
2397                 WARN_ON(idx == INVALID_INDEX);
2398                 clear_unsync_child_bit(sp, idx);
2399                 level++;
2400         } while (!sp->unsync_children);
2401 }
2402
2403 static void mmu_sync_children(struct kvm_vcpu *vcpu,
2404                               struct kvm_mmu_page *parent)
2405 {
2406         int i;
2407         struct kvm_mmu_page *sp;
2408         struct mmu_page_path parents;
2409         struct kvm_mmu_pages pages;
2410         LIST_HEAD(invalid_list);
2411         bool flush = false;
2412
2413         while (mmu_unsync_walk(parent, &pages)) {
2414                 bool protected = false;
2415
2416                 for_each_sp(pages, sp, parents, i)
2417                         protected |= rmap_write_protect(vcpu, sp->gfn);
2418
2419                 if (protected) {
2420                         kvm_flush_remote_tlbs(vcpu->kvm);
2421                         flush = false;
2422                 }
2423
2424                 for_each_sp(pages, sp, parents, i) {
2425                         flush |= kvm_sync_page(vcpu, sp, &invalid_list);
2426                         mmu_pages_clear_parents(&parents);
2427                 }
2428                 if (need_resched() || spin_needbreak(&vcpu->kvm->mmu_lock)) {
2429                         kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2430                         cond_resched_lock(&vcpu->kvm->mmu_lock);
2431                         flush = false;
2432                 }
2433         }
2434
2435         kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2436 }
2437
2438 static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2439 {
2440         atomic_set(&sp->write_flooding_count,  0);
2441 }
2442
2443 static void clear_sp_write_flooding_count(u64 *spte)
2444 {
2445         struct kvm_mmu_page *sp =  page_header(__pa(spte));
2446
2447         __clear_sp_write_flooding_count(sp);
2448 }
2449
2450 static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
2451                                              gfn_t gfn,
2452                                              gva_t gaddr,
2453                                              unsigned level,
2454                                              int direct,
2455                                              unsigned access)
2456 {
2457         union kvm_mmu_page_role role;
2458         unsigned quadrant;
2459         struct kvm_mmu_page *sp;
2460         bool need_sync = false;
2461         bool flush = false;
2462         int collisions = 0;
2463         LIST_HEAD(invalid_list);
2464
2465         role = vcpu->arch.mmu->mmu_role.base;
2466         role.level = level;
2467         role.direct = direct;
2468         if (role.direct)
2469                 role.gpte_is_8_bytes = true;
2470         role.access = access;
2471         if (!vcpu->arch.mmu->direct_map
2472             && vcpu->arch.mmu->root_level <= PT32_ROOT_LEVEL) {
2473                 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
2474                 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
2475                 role.quadrant = quadrant;
2476         }
2477         for_each_valid_sp(vcpu->kvm, sp, gfn) {
2478                 if (sp->gfn != gfn) {
2479                         collisions++;
2480                         continue;
2481                 }
2482
2483                 if (!need_sync && sp->unsync)
2484                         need_sync = true;
2485
2486                 if (sp->role.word != role.word)
2487                         continue;
2488
2489                 if (sp->unsync) {
2490                         /* The page is good, but __kvm_sync_page might still end
2491                          * up zapping it.  If so, break in order to rebuild it.
2492                          */
2493                         if (!__kvm_sync_page(vcpu, sp, &invalid_list))
2494                                 break;
2495
2496                         WARN_ON(!list_empty(&invalid_list));
2497                         kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2498                 }
2499
2500                 if (sp->unsync_children)
2501                         kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
2502
2503                 __clear_sp_write_flooding_count(sp);
2504                 trace_kvm_mmu_get_page(sp, false);
2505                 goto out;
2506         }
2507
2508         ++vcpu->kvm->stat.mmu_cache_miss;
2509
2510         sp = kvm_mmu_alloc_page(vcpu, direct);
2511
2512         sp->gfn = gfn;
2513         sp->role = role;
2514         hlist_add_head(&sp->hash_link,
2515                 &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)]);
2516         if (!direct) {
2517                 /*
2518                  * we should do write protection before syncing pages
2519                  * otherwise the content of the synced shadow page may
2520                  * be inconsistent with guest page table.
2521                  */
2522                 account_shadowed(vcpu->kvm, sp);
2523                 if (level == PT_PAGE_TABLE_LEVEL &&
2524                       rmap_write_protect(vcpu, gfn))
2525                         kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn, 1);
2526
2527                 if (level > PT_PAGE_TABLE_LEVEL && need_sync)
2528                         flush |= kvm_sync_pages(vcpu, gfn, &invalid_list);
2529         }
2530         clear_page(sp->spt);
2531         trace_kvm_mmu_get_page(sp, true);
2532
2533         kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2534 out:
2535         if (collisions > vcpu->kvm->stat.max_mmu_page_hash_collisions)
2536                 vcpu->kvm->stat.max_mmu_page_hash_collisions = collisions;
2537         return sp;
2538 }
2539
2540 static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2541                                         struct kvm_vcpu *vcpu, hpa_t root,
2542                                         u64 addr)
2543 {
2544         iterator->addr = addr;
2545         iterator->shadow_addr = root;
2546         iterator->level = vcpu->arch.mmu->shadow_root_level;
2547
2548         if (iterator->level == PT64_ROOT_4LEVEL &&
2549             vcpu->arch.mmu->root_level < PT64_ROOT_4LEVEL &&
2550             !vcpu->arch.mmu->direct_map)
2551                 --iterator->level;
2552
2553         if (iterator->level == PT32E_ROOT_LEVEL) {
2554                 /*
2555                  * prev_root is currently only used for 64-bit hosts. So only
2556                  * the active root_hpa is valid here.
2557                  */
2558                 BUG_ON(root != vcpu->arch.mmu->root_hpa);
2559
2560                 iterator->shadow_addr
2561                         = vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
2562                 iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
2563                 --iterator->level;
2564                 if (!iterator->shadow_addr)
2565                         iterator->level = 0;
2566         }
2567 }
2568
2569 static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2570                              struct kvm_vcpu *vcpu, u64 addr)
2571 {
2572         shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root_hpa,
2573                                     addr);
2574 }
2575
2576 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2577 {
2578         if (iterator->level < PT_PAGE_TABLE_LEVEL)
2579                 return false;
2580
2581         iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
2582         iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2583         return true;
2584 }
2585
2586 static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2587                                u64 spte)
2588 {
2589         if (is_last_spte(spte, iterator->level)) {
2590                 iterator->level = 0;
2591                 return;
2592         }
2593
2594         iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK;
2595         --iterator->level;
2596 }
2597
2598 static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2599 {
2600         __shadow_walk_next(iterator, *iterator->sptep);
2601 }
2602
2603 static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2604                              struct kvm_mmu_page *sp)
2605 {
2606         u64 spte;
2607
2608         BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2609
2610         spte = __pa(sp->spt) | shadow_present_mask | PT_WRITABLE_MASK |
2611                shadow_user_mask | shadow_x_mask | shadow_me_mask;
2612
2613         if (sp_ad_disabled(sp))
2614                 spte |= shadow_acc_track_value;
2615         else
2616                 spte |= shadow_accessed_mask;
2617
2618         mmu_spte_set(sptep, spte);
2619
2620         mmu_page_add_parent_pte(vcpu, sp, sptep);
2621
2622         if (sp->unsync_children || sp->unsync)
2623                 mark_unsync(sptep);
2624 }
2625
2626 static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2627                                    unsigned direct_access)
2628 {
2629         if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2630                 struct kvm_mmu_page *child;
2631
2632                 /*
2633                  * For the direct sp, if the guest pte's dirty bit
2634                  * changed form clean to dirty, it will corrupt the
2635                  * sp's access: allow writable in the read-only sp,
2636                  * so we should update the spte at this point to get
2637                  * a new sp with the correct access.
2638                  */
2639                 child = page_header(*sptep & PT64_BASE_ADDR_MASK);
2640                 if (child->role.access == direct_access)
2641                         return;
2642
2643                 drop_parent_pte(child, sptep);
2644                 kvm_flush_remote_tlbs_with_address(vcpu->kvm, child->gfn, 1);
2645         }
2646 }
2647
2648 static bool mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
2649                              u64 *spte)
2650 {
2651         u64 pte;
2652         struct kvm_mmu_page *child;
2653
2654         pte = *spte;
2655         if (is_shadow_present_pte(pte)) {
2656                 if (is_last_spte(pte, sp->role.level)) {
2657                         drop_spte(kvm, spte);
2658                         if (is_large_pte(pte))
2659                                 --kvm->stat.lpages;
2660                 } else {
2661                         child = page_header(pte & PT64_BASE_ADDR_MASK);
2662                         drop_parent_pte(child, spte);
2663                 }
2664                 return true;
2665         }
2666
2667         if (is_mmio_spte(pte))
2668                 mmu_spte_clear_no_track(spte);
2669
2670         return false;
2671 }
2672
2673 static void kvm_mmu_page_unlink_children(struct kvm *kvm,
2674                                          struct kvm_mmu_page *sp)
2675 {
2676         unsigned i;
2677
2678         for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
2679                 mmu_page_zap_pte(kvm, sp, sp->spt + i);
2680 }
2681
2682 static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
2683 {
2684         u64 *sptep;
2685         struct rmap_iterator iter;
2686
2687         while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2688                 drop_parent_pte(sp, sptep);
2689 }
2690
2691 static int mmu_zap_unsync_children(struct kvm *kvm,
2692                                    struct kvm_mmu_page *parent,
2693                                    struct list_head *invalid_list)
2694 {
2695         int i, zapped = 0;
2696         struct mmu_page_path parents;
2697         struct kvm_mmu_pages pages;
2698
2699         if (parent->role.level == PT_PAGE_TABLE_LEVEL)
2700                 return 0;
2701
2702         while (mmu_unsync_walk(parent, &pages)) {
2703                 struct kvm_mmu_page *sp;
2704
2705                 for_each_sp(pages, sp, parents, i) {
2706                         kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2707                         mmu_pages_clear_parents(&parents);
2708                         zapped++;
2709                 }
2710         }
2711
2712         return zapped;
2713 }
2714
2715 static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
2716                                        struct kvm_mmu_page *sp,
2717                                        struct list_head *invalid_list,
2718                                        int *nr_zapped)
2719 {
2720         bool list_unstable;
2721
2722         trace_kvm_mmu_prepare_zap_page(sp);
2723         ++kvm->stat.mmu_shadow_zapped;
2724         *nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
2725         kvm_mmu_page_unlink_children(kvm, sp);
2726         kvm_mmu_unlink_parents(kvm, sp);
2727
2728         /* Zapping children means active_mmu_pages has become unstable. */
2729         list_unstable = *nr_zapped;
2730
2731         if (!sp->role.invalid && !sp->role.direct)
2732                 unaccount_shadowed(kvm, sp);
2733
2734         if (sp->unsync)
2735                 kvm_unlink_unsync_page(kvm, sp);
2736         if (!sp->root_count) {
2737                 /* Count self */
2738                 (*nr_zapped)++;
2739                 list_move(&sp->link, invalid_list);
2740                 kvm_mod_used_mmu_pages(kvm, -1);
2741         } else {
2742                 list_move(&sp->link, &kvm->arch.active_mmu_pages);
2743
2744                 if (!sp->role.invalid)
2745                         kvm_reload_remote_mmus(kvm);
2746         }
2747
2748         sp->role.invalid = 1;
2749         return list_unstable;
2750 }
2751
2752 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2753                                      struct list_head *invalid_list)
2754 {
2755         int nr_zapped;
2756
2757         __kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
2758         return nr_zapped;
2759 }
2760
2761 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2762                                     struct list_head *invalid_list)
2763 {
2764         struct kvm_mmu_page *sp, *nsp;
2765
2766         if (list_empty(invalid_list))
2767                 return;
2768
2769         /*
2770          * We need to make sure everyone sees our modifications to
2771          * the page tables and see changes to vcpu->mode here. The barrier
2772          * in the kvm_flush_remote_tlbs() achieves this. This pairs
2773          * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2774          *
2775          * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2776          * guest mode and/or lockless shadow page table walks.
2777          */
2778         kvm_flush_remote_tlbs(kvm);
2779
2780         list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2781                 WARN_ON(!sp->role.invalid || sp->root_count);
2782                 kvm_mmu_free_page(sp);
2783         }
2784 }
2785
2786 static bool prepare_zap_oldest_mmu_page(struct kvm *kvm,
2787                                         struct list_head *invalid_list)
2788 {
2789         struct kvm_mmu_page *sp;
2790
2791         if (list_empty(&kvm->arch.active_mmu_pages))
2792                 return false;
2793
2794         sp = list_last_entry(&kvm->arch.active_mmu_pages,
2795                              struct kvm_mmu_page, link);
2796         return kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2797 }
2798
2799 /*
2800  * Changing the number of mmu pages allocated to the vm
2801  * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2802  */
2803 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
2804 {
2805         LIST_HEAD(invalid_list);
2806
2807         spin_lock(&kvm->mmu_lock);
2808
2809         if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
2810                 /* Need to free some mmu pages to achieve the goal. */
2811                 while (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages)
2812                         if (!prepare_zap_oldest_mmu_page(kvm, &invalid_list))
2813                                 break;
2814
2815                 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2816                 goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2817         }
2818
2819         kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2820
2821         spin_unlock(&kvm->mmu_lock);
2822 }
2823
2824 int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2825 {
2826         struct kvm_mmu_page *sp;
2827         LIST_HEAD(invalid_list);
2828         int r;
2829
2830         pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
2831         r = 0;
2832         spin_lock(&kvm->mmu_lock);
2833         for_each_gfn_indirect_valid_sp(kvm, sp, gfn) {
2834                 pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
2835                          sp->role.word);
2836                 r = 1;
2837                 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2838         }
2839         kvm_mmu_commit_zap_page(kvm, &invalid_list);
2840         spin_unlock(&kvm->mmu_lock);
2841
2842         return r;
2843 }
2844 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page);
2845
2846 static void kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
2847 {
2848         trace_kvm_mmu_unsync_page(sp);
2849         ++vcpu->kvm->stat.mmu_unsync;
2850         sp->unsync = 1;
2851
2852         kvm_mmu_mark_parents_unsync(sp);
2853 }
2854
2855 static bool mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
2856                                    bool can_unsync)
2857 {
2858         struct kvm_mmu_page *sp;
2859
2860         if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
2861                 return true;
2862
2863         for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
2864                 if (!can_unsync)
2865                         return true;
2866
2867                 if (sp->unsync)
2868                         continue;
2869
2870                 WARN_ON(sp->role.level != PT_PAGE_TABLE_LEVEL);
2871                 kvm_unsync_page(vcpu, sp);
2872         }
2873
2874         /*
2875          * We need to ensure that the marking of unsync pages is visible
2876          * before the SPTE is updated to allow writes because
2877          * kvm_mmu_sync_roots() checks the unsync flags without holding
2878          * the MMU lock and so can race with this. If the SPTE was updated
2879          * before the page had been marked as unsync-ed, something like the
2880          * following could happen:
2881          *
2882          * CPU 1                    CPU 2
2883          * ---------------------------------------------------------------------
2884          * 1.2 Host updates SPTE
2885          *     to be writable
2886          *                      2.1 Guest writes a GPTE for GVA X.
2887          *                          (GPTE being in the guest page table shadowed
2888          *                           by the SP from CPU 1.)
2889          *                          This reads SPTE during the page table walk.
2890          *                          Since SPTE.W is read as 1, there is no
2891          *                          fault.
2892          *
2893          *                      2.2 Guest issues TLB flush.
2894          *                          That causes a VM Exit.
2895          *
2896          *                      2.3 kvm_mmu_sync_pages() reads sp->unsync.
2897          *                          Since it is false, so it just returns.
2898          *
2899          *                      2.4 Guest accesses GVA X.
2900          *                          Since the mapping in the SP was not updated,
2901          *                          so the old mapping for GVA X incorrectly
2902          *                          gets used.
2903          * 1.1 Host marks SP
2904          *     as unsync
2905          *     (sp->unsync = true)
2906          *
2907          * The write barrier below ensures that 1.1 happens before 1.2 and thus
2908          * the situation in 2.4 does not arise. The implicit barrier in 2.2
2909          * pairs with this write barrier.
2910          */
2911         smp_wmb();
2912
2913         return false;
2914 }
2915
2916 static bool kvm_is_mmio_pfn(kvm_pfn_t pfn)
2917 {
2918         if (pfn_valid(pfn))
2919                 return !is_zero_pfn(pfn) && PageReserved(pfn_to_page(pfn)) &&
2920                         /*
2921                          * Some reserved pages, such as those from NVDIMM
2922                          * DAX devices, are not for MMIO, and can be mapped
2923                          * with cached memory type for better performance.
2924                          * However, the above check misconceives those pages
2925                          * as MMIO, and results in KVM mapping them with UC
2926                          * memory type, which would hurt the performance.
2927                          * Therefore, we check the host memory type in addition
2928                          * and only treat UC/UC-/WC pages as MMIO.
2929                          */
2930                         (!pat_enabled() || pat_pfn_immune_to_uc_mtrr(pfn));
2931
2932         return !e820__mapped_raw_any(pfn_to_hpa(pfn),
2933                                      pfn_to_hpa(pfn + 1) - 1,
2934                                      E820_TYPE_RAM);
2935 }
2936
2937 /* Bits which may be returned by set_spte() */
2938 #define SET_SPTE_WRITE_PROTECTED_PT     BIT(0)
2939 #define SET_SPTE_NEED_REMOTE_TLB_FLUSH  BIT(1)
2940
2941 static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2942                     unsigned pte_access, int level,
2943                     gfn_t gfn, kvm_pfn_t pfn, bool speculative,
2944                     bool can_unsync, bool host_writable)
2945 {
2946         u64 spte = 0;
2947         int ret = 0;
2948         struct kvm_mmu_page *sp;
2949
2950         if (set_mmio_spte(vcpu, sptep, gfn, pfn, pte_access))
2951                 return 0;
2952
2953         sp = page_header(__pa(sptep));
2954         if (sp_ad_disabled(sp))
2955                 spte |= shadow_acc_track_value;
2956
2957         /*
2958          * For the EPT case, shadow_present_mask is 0 if hardware
2959          * supports exec-only page table entries.  In that case,
2960          * ACC_USER_MASK and shadow_user_mask are used to represent
2961          * read access.  See FNAME(gpte_access) in paging_tmpl.h.
2962          */
2963         spte |= shadow_present_mask;
2964         if (!speculative)
2965                 spte |= spte_shadow_accessed_mask(spte);
2966
2967         if (pte_access & ACC_EXEC_MASK)
2968                 spte |= shadow_x_mask;
2969         else
2970                 spte |= shadow_nx_mask;
2971
2972         if (pte_access & ACC_USER_MASK)
2973                 spte |= shadow_user_mask;
2974
2975         if (level > PT_PAGE_TABLE_LEVEL)
2976                 spte |= PT_PAGE_SIZE_MASK;
2977         if (tdp_enabled)
2978                 spte |= kvm_x86_ops->get_mt_mask(vcpu, gfn,
2979                         kvm_is_mmio_pfn(pfn));
2980
2981         if (host_writable)
2982                 spte |= SPTE_HOST_WRITEABLE;
2983         else
2984                 pte_access &= ~ACC_WRITE_MASK;
2985
2986         if (!kvm_is_mmio_pfn(pfn))
2987                 spte |= shadow_me_mask;
2988
2989         spte |= (u64)pfn << PAGE_SHIFT;
2990
2991         if (pte_access & ACC_WRITE_MASK) {
2992
2993                 /*
2994                  * Other vcpu creates new sp in the window between
2995                  * mapping_level() and acquiring mmu-lock. We can
2996                  * allow guest to retry the access, the mapping can
2997                  * be fixed if guest refault.
2998                  */
2999                 if (level > PT_PAGE_TABLE_LEVEL &&
3000                     mmu_gfn_lpage_is_disallowed(vcpu, gfn, level))
3001                         goto done;
3002
3003                 spte |= PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE;
3004
3005                 /*
3006                  * Optimization: for pte sync, if spte was writable the hash
3007                  * lookup is unnecessary (and expensive). Write protection
3008                  * is responsibility of mmu_get_page / kvm_sync_page.
3009                  * Same reasoning can be applied to dirty page accounting.
3010                  */
3011                 if (!can_unsync && is_writable_pte(*sptep))
3012                         goto set_pte;
3013
3014                 if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
3015                         pgprintk("%s: found shadow page for %llx, marking ro\n",
3016                                  __func__, gfn);
3017                         ret |= SET_SPTE_WRITE_PROTECTED_PT;
3018                         pte_access &= ~ACC_WRITE_MASK;
3019                         spte &= ~(PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE);
3020                 }
3021         }
3022
3023         if (pte_access & ACC_WRITE_MASK) {
3024                 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3025                 spte |= spte_shadow_dirty_mask(spte);
3026         }
3027
3028         if (speculative)
3029                 spte = mark_spte_for_access_track(spte);
3030
3031 set_pte:
3032         if (mmu_spte_update(sptep, spte))
3033                 ret |= SET_SPTE_NEED_REMOTE_TLB_FLUSH;
3034 done:
3035         return ret;
3036 }
3037
3038 static int mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep, unsigned pte_access,
3039                         int write_fault, int level, gfn_t gfn, kvm_pfn_t pfn,
3040                         bool speculative, bool host_writable)
3041 {
3042         int was_rmapped = 0;
3043         int rmap_count;
3044         int set_spte_ret;
3045         int ret = RET_PF_RETRY;
3046         bool flush = false;
3047
3048         pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
3049                  *sptep, write_fault, gfn);
3050
3051         if (is_shadow_present_pte(*sptep)) {
3052                 /*
3053                  * If we overwrite a PTE page pointer with a 2MB PMD, unlink
3054                  * the parent of the now unreachable PTE.
3055                  */
3056                 if (level > PT_PAGE_TABLE_LEVEL &&
3057                     !is_large_pte(*sptep)) {
3058                         struct kvm_mmu_page *child;
3059                         u64 pte = *sptep;
3060
3061                         child = page_header(pte & PT64_BASE_ADDR_MASK);
3062                         drop_parent_pte(child, sptep);
3063                         flush = true;
3064                 } else if (pfn != spte_to_pfn(*sptep)) {
3065                         pgprintk("hfn old %llx new %llx\n",
3066                                  spte_to_pfn(*sptep), pfn);
3067                         drop_spte(vcpu->kvm, sptep);
3068                         flush = true;
3069                 } else
3070                         was_rmapped = 1;
3071         }
3072
3073         set_spte_ret = set_spte(vcpu, sptep, pte_access, level, gfn, pfn,
3074                                 speculative, true, host_writable);
3075         if (set_spte_ret & SET_SPTE_WRITE_PROTECTED_PT) {
3076                 if (write_fault)
3077                         ret = RET_PF_EMULATE;
3078                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
3079         }
3080
3081         if (set_spte_ret & SET_SPTE_NEED_REMOTE_TLB_FLUSH || flush)
3082                 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn,
3083                                 KVM_PAGES_PER_HPAGE(level));
3084
3085         if (unlikely(is_mmio_spte(*sptep)))
3086                 ret = RET_PF_EMULATE;
3087
3088         pgprintk("%s: setting spte %llx\n", __func__, *sptep);
3089         pgprintk("instantiating %s PTE (%s) at %llx (%llx) addr %p\n",
3090                  is_large_pte(*sptep)? "2MB" : "4kB",
3091                  *sptep & PT_WRITABLE_MASK ? "RW" : "R", gfn,
3092                  *sptep, sptep);
3093         if (!was_rmapped && is_large_pte(*sptep))
3094                 ++vcpu->kvm->stat.lpages;
3095
3096         if (is_shadow_present_pte(*sptep)) {
3097                 if (!was_rmapped) {
3098                         rmap_count = rmap_add(vcpu, sptep, gfn);
3099                         if (rmap_count > RMAP_RECYCLE_THRESHOLD)
3100                                 rmap_recycle(vcpu, sptep, gfn);
3101                 }
3102         }
3103
3104         return ret;
3105 }
3106
3107 static kvm_pfn_t pte_prefetch_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn,
3108                                      bool no_dirty_log)
3109 {
3110         struct kvm_memory_slot *slot;
3111
3112         slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, no_dirty_log);
3113         if (!slot)
3114                 return KVM_PFN_ERR_FAULT;
3115
3116         return gfn_to_pfn_memslot_atomic(slot, gfn);
3117 }
3118
3119 static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
3120                                     struct kvm_mmu_page *sp,
3121                                     u64 *start, u64 *end)
3122 {
3123         struct page *pages[PTE_PREFETCH_NUM];
3124         struct kvm_memory_slot *slot;
3125         unsigned access = sp->role.access;
3126         int i, ret;
3127         gfn_t gfn;
3128
3129         gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
3130         slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
3131         if (!slot)
3132                 return -1;
3133
3134         ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
3135         if (ret <= 0)
3136                 return -1;
3137
3138         for (i = 0; i < ret; i++, gfn++, start++) {
3139                 mmu_set_spte(vcpu, start, access, 0, sp->role.level, gfn,
3140                              page_to_pfn(pages[i]), true, true);
3141                 put_page(pages[i]);
3142         }
3143
3144         return 0;
3145 }
3146
3147 static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
3148                                   struct kvm_mmu_page *sp, u64 *sptep)
3149 {
3150         u64 *spte, *start = NULL;
3151         int i;
3152
3153         WARN_ON(!sp->role.direct);
3154
3155         i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
3156         spte = sp->spt + i;
3157
3158         for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
3159                 if (is_shadow_present_pte(*spte) || spte == sptep) {
3160                         if (!start)
3161                                 continue;
3162                         if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
3163                                 break;
3164                         start = NULL;
3165                 } else if (!start)
3166                         start = spte;
3167         }
3168 }
3169
3170 static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
3171 {
3172         struct kvm_mmu_page *sp;
3173
3174         sp = page_header(__pa(sptep));
3175
3176         /*
3177          * Without accessed bits, there's no way to distinguish between
3178          * actually accessed translations and prefetched, so disable pte
3179          * prefetch if accessed bits aren't available.
3180          */
3181         if (sp_ad_disabled(sp))
3182                 return;
3183
3184         if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3185                 return;
3186
3187         __direct_pte_prefetch(vcpu, sp, sptep);
3188 }
3189
3190 static int __direct_map(struct kvm_vcpu *vcpu, gpa_t gpa, int write,
3191                         int map_writable, int level, kvm_pfn_t pfn,
3192                         bool prefault)
3193 {
3194         struct kvm_shadow_walk_iterator it;
3195         struct kvm_mmu_page *sp;
3196         int ret;
3197         gfn_t gfn = gpa >> PAGE_SHIFT;
3198         gfn_t base_gfn = gfn;
3199
3200         if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3201                 return RET_PF_RETRY;
3202
3203         for_each_shadow_entry(vcpu, gpa, it) {
3204                 base_gfn = gfn & ~(KVM_PAGES_PER_HPAGE(it.level) - 1);
3205                 if (it.level == level)
3206                         break;
3207
3208                 drop_large_spte(vcpu, it.sptep);
3209                 if (!is_shadow_present_pte(*it.sptep)) {
3210                         sp = kvm_mmu_get_page(vcpu, base_gfn, it.addr,
3211                                               it.level - 1, true, ACC_ALL);
3212
3213                         link_shadow_page(vcpu, it.sptep, sp);
3214                 }
3215         }
3216
3217         ret = mmu_set_spte(vcpu, it.sptep, ACC_ALL,
3218                            write, level, base_gfn, pfn, prefault,
3219                            map_writable);
3220         direct_pte_prefetch(vcpu, it.sptep);
3221         ++vcpu->stat.pf_fixed;
3222         return ret;
3223 }
3224
3225 static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
3226 {
3227         send_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, PAGE_SHIFT, tsk);
3228 }
3229
3230 static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)
3231 {
3232         /*
3233          * Do not cache the mmio info caused by writing the readonly gfn
3234          * into the spte otherwise read access on readonly gfn also can
3235          * caused mmio page fault and treat it as mmio access.
3236          */
3237         if (pfn == KVM_PFN_ERR_RO_FAULT)
3238                 return RET_PF_EMULATE;
3239
3240         if (pfn == KVM_PFN_ERR_HWPOISON) {
3241                 kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu, gfn), current);
3242                 return RET_PF_RETRY;
3243         }
3244
3245         return -EFAULT;
3246 }
3247
3248 static void transparent_hugepage_adjust(struct kvm_vcpu *vcpu,
3249                                         gfn_t gfn, kvm_pfn_t *pfnp,
3250                                         int *levelp)
3251 {
3252         kvm_pfn_t pfn = *pfnp;
3253         int level = *levelp;
3254
3255         /*
3256          * Check if it's a transparent hugepage. If this would be an
3257          * hugetlbfs page, level wouldn't be set to
3258          * PT_PAGE_TABLE_LEVEL and there would be no adjustment done
3259          * here.
3260          */
3261         if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn) &&
3262             level == PT_PAGE_TABLE_LEVEL &&
3263             PageTransCompoundMap(pfn_to_page(pfn)) &&
3264             !mmu_gfn_lpage_is_disallowed(vcpu, gfn, PT_DIRECTORY_LEVEL)) {
3265                 unsigned long mask;
3266                 /*
3267                  * mmu_notifier_retry was successful and we hold the
3268                  * mmu_lock here, so the pmd can't become splitting
3269                  * from under us, and in turn
3270                  * __split_huge_page_refcount() can't run from under
3271                  * us and we can safely transfer the refcount from
3272                  * PG_tail to PG_head as we switch the pfn to tail to
3273                  * head.
3274                  */
3275                 *levelp = level = PT_DIRECTORY_LEVEL;
3276                 mask = KVM_PAGES_PER_HPAGE(level) - 1;
3277                 VM_BUG_ON((gfn & mask) != (pfn & mask));
3278                 if (pfn & mask) {
3279                         kvm_release_pfn_clean(pfn);
3280                         pfn &= ~mask;
3281                         kvm_get_pfn(pfn);
3282                         *pfnp = pfn;
3283                 }
3284         }
3285 }
3286
3287 static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
3288                                 kvm_pfn_t pfn, unsigned access, int *ret_val)
3289 {
3290         /* The pfn is invalid, report the error! */
3291         if (unlikely(is_error_pfn(pfn))) {
3292                 *ret_val = kvm_handle_bad_page(vcpu, gfn, pfn);
3293                 return true;
3294         }
3295
3296         if (unlikely(is_noslot_pfn(pfn)))
3297                 vcpu_cache_mmio_info(vcpu, gva, gfn, access);
3298
3299         return false;
3300 }
3301
3302 static bool page_fault_can_be_fast(u32 error_code)
3303 {
3304         /*
3305          * Do not fix the mmio spte with invalid generation number which
3306          * need to be updated by slow page fault path.
3307          */
3308         if (unlikely(error_code & PFERR_RSVD_MASK))
3309                 return false;
3310
3311         /* See if the page fault is due to an NX violation */
3312         if (unlikely(((error_code & (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))
3313                       == (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))))
3314                 return false;
3315
3316         /*
3317          * #PF can be fast if:
3318          * 1. The shadow page table entry is not present, which could mean that
3319          *    the fault is potentially caused by access tracking (if enabled).
3320          * 2. The shadow page table entry is present and the fault
3321          *    is caused by write-protect, that means we just need change the W
3322          *    bit of the spte which can be done out of mmu-lock.
3323          *
3324          * However, if access tracking is disabled we know that a non-present
3325          * page must be a genuine page fault where we have to create a new SPTE.
3326          * So, if access tracking is disabled, we return true only for write
3327          * accesses to a present page.
3328          */
3329
3330         return shadow_acc_track_mask != 0 ||
3331                ((error_code & (PFERR_WRITE_MASK | PFERR_PRESENT_MASK))
3332                 == (PFERR_WRITE_MASK | PFERR_PRESENT_MASK));
3333 }
3334
3335 /*
3336  * Returns true if the SPTE was fixed successfully. Otherwise,
3337  * someone else modified the SPTE from its original value.
3338  */
3339 static bool
3340 fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
3341                         u64 *sptep, u64 old_spte, u64 new_spte)
3342 {
3343         gfn_t gfn;
3344
3345         WARN_ON(!sp->role.direct);
3346
3347         /*
3348          * Theoretically we could also set dirty bit (and flush TLB) here in
3349          * order to eliminate unnecessary PML logging. See comments in
3350          * set_spte. But fast_page_fault is very unlikely to happen with PML
3351          * enabled, so we do not do this. This might result in the same GPA
3352          * to be logged in PML buffer again when the write really happens, and
3353          * eventually to be called by mark_page_dirty twice. But it's also no
3354          * harm. This also avoids the TLB flush needed after setting dirty bit
3355          * so non-PML cases won't be impacted.
3356          *
3357          * Compare with set_spte where instead shadow_dirty_mask is set.
3358          */
3359         if (cmpxchg64(sptep, old_spte, new_spte) != old_spte)
3360                 return false;
3361
3362         if (is_writable_pte(new_spte) && !is_writable_pte(old_spte)) {
3363                 /*
3364                  * The gfn of direct spte is stable since it is
3365                  * calculated by sp->gfn.
3366                  */
3367                 gfn = kvm_mmu_page_get_gfn(sp, sptep - sp->spt);
3368                 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3369         }
3370
3371         return true;
3372 }
3373
3374 static bool is_access_allowed(u32 fault_err_code, u64 spte)
3375 {
3376         if (fault_err_code & PFERR_FETCH_MASK)
3377                 return is_executable_pte(spte);
3378
3379         if (fault_err_code & PFERR_WRITE_MASK)
3380                 return is_writable_pte(spte);
3381
3382         /* Fault was on Read access */
3383         return spte & PT_PRESENT_MASK;
3384 }
3385
3386 /*
3387  * Return value:
3388  * - true: let the vcpu to access on the same address again.
3389  * - false: let the real page fault path to fix it.
3390  */
3391 static bool fast_page_fault(struct kvm_vcpu *vcpu, gva_t gva, int level,
3392                             u32 error_code)
3393 {
3394         struct kvm_shadow_walk_iterator iterator;
3395         struct kvm_mmu_page *sp;
3396         bool fault_handled = false;
3397         u64 spte = 0ull;
3398         uint retry_count = 0;
3399
3400         if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3401                 return false;
3402
3403         if (!page_fault_can_be_fast(error_code))
3404                 return false;
3405
3406         walk_shadow_page_lockless_begin(vcpu);
3407
3408         do {
3409                 u64 new_spte;
3410
3411                 for_each_shadow_entry_lockless(vcpu, gva, iterator, spte)
3412                         if (!is_shadow_present_pte(spte) ||
3413                             iterator.level < level)
3414                                 break;
3415
3416                 sp = page_header(__pa(iterator.sptep));
3417                 if (!is_last_spte(spte, sp->role.level))
3418                         break;
3419
3420                 /*
3421                  * Check whether the memory access that caused the fault would
3422                  * still cause it if it were to be performed right now. If not,
3423                  * then this is a spurious fault caused by TLB lazily flushed,
3424                  * or some other CPU has already fixed the PTE after the
3425                  * current CPU took the fault.
3426                  *
3427                  * Need not check the access of upper level table entries since
3428                  * they are always ACC_ALL.
3429                  */
3430                 if (is_access_allowed(error_code, spte)) {
3431                         fault_handled = true;
3432                         break;
3433                 }
3434
3435                 new_spte = spte;
3436
3437                 if (is_access_track_spte(spte))
3438                         new_spte = restore_acc_track_spte(new_spte);
3439
3440                 /*
3441                  * Currently, to simplify the code, write-protection can
3442                  * be removed in the fast path only if the SPTE was
3443                  * write-protected for dirty-logging or access tracking.
3444                  */
3445                 if ((error_code & PFERR_WRITE_MASK) &&
3446                     spte_can_locklessly_be_made_writable(spte))
3447                 {
3448                         new_spte |= PT_WRITABLE_MASK;
3449
3450                         /*
3451                          * Do not fix write-permission on the large spte.  Since
3452                          * we only dirty the first page into the dirty-bitmap in
3453                          * fast_pf_fix_direct_spte(), other pages are missed
3454                          * if its slot has dirty logging enabled.
3455                          *
3456                          * Instead, we let the slow page fault path create a
3457                          * normal spte to fix the access.
3458                          *
3459                          * See the comments in kvm_arch_commit_memory_region().
3460                          */
3461                         if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3462                                 break;
3463                 }
3464
3465                 /* Verify that the fault can be handled in the fast path */
3466                 if (new_spte == spte ||
3467                     !is_access_allowed(error_code, new_spte))
3468                         break;
3469
3470                 /*
3471                  * Currently, fast page fault only works for direct mapping
3472                  * since the gfn is not stable for indirect shadow page. See
3473                  * Documentation/virtual/kvm/locking.txt to get more detail.
3474                  */
3475                 fault_handled = fast_pf_fix_direct_spte(vcpu, sp,
3476                                                         iterator.sptep, spte,
3477                                                         new_spte);
3478                 if (fault_handled)
3479                         break;
3480
3481                 if (++retry_count > 4) {
3482                         printk_once(KERN_WARNING
3483                                 "kvm: Fast #PF retrying more than 4 times.\n");
3484                         break;
3485                 }
3486
3487         } while (true);
3488
3489         trace_fast_page_fault(vcpu, gva, error_code, iterator.sptep,
3490                               spte, fault_handled);
3491         walk_shadow_page_lockless_end(vcpu);
3492
3493         return fault_handled;
3494 }
3495
3496 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
3497                          gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable);
3498 static int make_mmu_pages_available(struct kvm_vcpu *vcpu);
3499
3500 static int nonpaging_map(struct kvm_vcpu *vcpu, gva_t v, u32 error_code,
3501                          gfn_t gfn, bool prefault)
3502 {
3503         int r;
3504         int level;
3505         bool force_pt_level = false;
3506         kvm_pfn_t pfn;
3507         unsigned long mmu_seq;
3508         bool map_writable, write = error_code & PFERR_WRITE_MASK;
3509
3510         level = mapping_level(vcpu, gfn, &force_pt_level);
3511         if (likely(!force_pt_level)) {
3512                 /*
3513                  * This path builds a PAE pagetable - so we can map
3514                  * 2mb pages at maximum. Therefore check if the level
3515                  * is larger than that.
3516                  */
3517                 if (level > PT_DIRECTORY_LEVEL)
3518                         level = PT_DIRECTORY_LEVEL;
3519
3520                 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
3521         }
3522
3523         if (fast_page_fault(vcpu, v, level, error_code))
3524                 return RET_PF_RETRY;
3525
3526         mmu_seq = vcpu->kvm->mmu_notifier_seq;
3527         smp_rmb();
3528
3529         if (try_async_pf(vcpu, prefault, gfn, v, &pfn, write, &map_writable))
3530                 return RET_PF_RETRY;
3531
3532         if (handle_abnormal_pfn(vcpu, v, gfn, pfn, ACC_ALL, &r))
3533                 return r;
3534
3535         r = RET_PF_RETRY;
3536         spin_lock(&vcpu->kvm->mmu_lock);
3537         if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
3538                 goto out_unlock;
3539         if (make_mmu_pages_available(vcpu) < 0)
3540                 goto out_unlock;
3541         if (likely(!force_pt_level))
3542                 transparent_hugepage_adjust(vcpu, gfn, &pfn, &level);
3543         r = __direct_map(vcpu, v, write, map_writable, level, pfn, prefault);
3544 out_unlock:
3545         spin_unlock(&vcpu->kvm->mmu_lock);
3546         kvm_release_pfn_clean(pfn);
3547         return r;
3548 }
3549
3550 static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3551                                struct list_head *invalid_list)
3552 {
3553         struct kvm_mmu_page *sp;
3554
3555         if (!VALID_PAGE(*root_hpa))
3556                 return;
3557
3558         sp = page_header(*root_hpa & PT64_BASE_ADDR_MASK);
3559         --sp->root_count;
3560         if (!sp->root_count && sp->role.invalid)
3561                 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3562
3563         *root_hpa = INVALID_PAGE;
3564 }
3565
3566 /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
3567 void kvm_mmu_free_roots(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
3568                         ulong roots_to_free)
3569 {
3570         int i;
3571         LIST_HEAD(invalid_list);
3572         bool free_active_root = roots_to_free & KVM_MMU_ROOT_CURRENT;
3573
3574         BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3575
3576         /* Before acquiring the MMU lock, see if we need to do any real work. */
3577         if (!(free_active_root && VALID_PAGE(mmu->root_hpa))) {
3578                 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3579                         if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3580                             VALID_PAGE(mmu->prev_roots[i].hpa))
3581                                 break;
3582
3583                 if (i == KVM_MMU_NUM_PREV_ROOTS)
3584                         return;
3585         }
3586
3587         spin_lock(&vcpu->kvm->mmu_lock);
3588
3589         for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3590                 if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
3591                         mmu_free_root_page(vcpu->kvm, &mmu->prev_roots[i].hpa,
3592                                            &invalid_list);
3593
3594         if (free_active_root) {
3595                 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
3596                     (mmu->root_level >= PT64_ROOT_4LEVEL || mmu->direct_map)) {
3597                         mmu_free_root_page(vcpu->kvm, &mmu->root_hpa,
3598                                            &invalid_list);
3599                 } else {
3600                         for (i = 0; i < 4; ++i)
3601                                 if (mmu->pae_root[i] != 0)
3602                                         mmu_free_root_page(vcpu->kvm,
3603                                                            &mmu->pae_root[i],
3604                                                            &invalid_list);
3605                         mmu->root_hpa = INVALID_PAGE;
3606                 }
3607                 mmu->root_cr3 = 0;
3608         }
3609
3610         kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
3611         spin_unlock(&vcpu->kvm->mmu_lock);
3612 }
3613 EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3614
3615 static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3616 {
3617         int ret = 0;
3618
3619         if (!kvm_is_visible_gfn(vcpu->kvm, root_gfn)) {
3620                 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3621                 ret = 1;
3622         }
3623
3624         return ret;
3625 }
3626
3627 static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3628 {
3629         struct kvm_mmu_page *sp;
3630         unsigned i;
3631
3632         if (vcpu->arch.mmu->shadow_root_level >= PT64_ROOT_4LEVEL) {
3633                 spin_lock(&vcpu->kvm->mmu_lock);
3634                 if(make_mmu_pages_available(vcpu) < 0) {
3635                         spin_unlock(&vcpu->kvm->mmu_lock);
3636                         return -ENOSPC;
3637                 }
3638                 sp = kvm_mmu_get_page(vcpu, 0, 0,
3639                                 vcpu->arch.mmu->shadow_root_level, 1, ACC_ALL);
3640                 ++sp->root_count;
3641                 spin_unlock(&vcpu->kvm->mmu_lock);
3642                 vcpu->arch.mmu->root_hpa = __pa(sp->spt);
3643         } else if (vcpu->arch.mmu->shadow_root_level == PT32E_ROOT_LEVEL) {
3644                 for (i = 0; i < 4; ++i) {
3645                         hpa_t root = vcpu->arch.mmu->pae_root[i];
3646
3647                         MMU_WARN_ON(VALID_PAGE(root));
3648                         spin_lock(&vcpu->kvm->mmu_lock);
3649                         if (make_mmu_pages_available(vcpu) < 0) {
3650                                 spin_unlock(&vcpu->kvm->mmu_lock);
3651                                 return -ENOSPC;
3652                         }
3653                         sp = kvm_mmu_get_page(vcpu, i << (30 - PAGE_SHIFT),
3654                                         i << 30, PT32_ROOT_LEVEL, 1, ACC_ALL);
3655                         root = __pa(sp->spt);
3656                         ++sp->root_count;
3657                         spin_unlock(&vcpu->kvm->mmu_lock);
3658                         vcpu->arch.mmu->pae_root[i] = root | PT_PRESENT_MASK;
3659                 }
3660                 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3661         } else
3662                 BUG();
3663         vcpu->arch.mmu->root_cr3 = vcpu->arch.mmu->get_cr3(vcpu);
3664
3665         return 0;
3666 }
3667
3668 static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3669 {
3670         struct kvm_mmu_page *sp;
3671         u64 pdptr, pm_mask;
3672         gfn_t root_gfn, root_cr3;
3673         int i;
3674
3675         root_cr3 = vcpu->arch.mmu->get_cr3(vcpu);
3676         root_gfn = root_cr3 >> PAGE_SHIFT;
3677
3678         if (mmu_check_root(vcpu, root_gfn))
3679                 return 1;
3680
3681         /*
3682          * Do we shadow a long mode page table? If so we need to
3683          * write-protect the guests page table root.
3684          */
3685         if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3686                 hpa_t root = vcpu->arch.mmu->root_hpa;
3687
3688                 MMU_WARN_ON(VALID_PAGE(root));
3689
3690                 spin_lock(&vcpu->kvm->mmu_lock);
3691                 if (make_mmu_pages_available(vcpu) < 0) {
3692                         spin_unlock(&vcpu->kvm->mmu_lock);
3693                         return -ENOSPC;
3694                 }
3695                 sp = kvm_mmu_get_page(vcpu, root_gfn, 0,
3696                                 vcpu->arch.mmu->shadow_root_level, 0, ACC_ALL);
3697                 root = __pa(sp->spt);
3698                 ++sp->root_count;
3699                 spin_unlock(&vcpu->kvm->mmu_lock);
3700                 vcpu->arch.mmu->root_hpa = root;
3701                 goto set_root_cr3;
3702         }
3703
3704         /*
3705          * We shadow a 32 bit page table. This may be a legacy 2-level
3706          * or a PAE 3-level page table. In either case we need to be aware that
3707          * the shadow page table may be a PAE or a long mode page table.
3708          */
3709         pm_mask = PT_PRESENT_MASK;
3710         if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL)
3711                 pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3712
3713         for (i = 0; i < 4; ++i) {
3714                 hpa_t root = vcpu->arch.mmu->pae_root[i];
3715
3716                 MMU_WARN_ON(VALID_PAGE(root));
3717                 if (vcpu->arch.mmu->root_level == PT32E_ROOT_LEVEL) {
3718                         pdptr = vcpu->arch.mmu->get_pdptr(vcpu, i);
3719                         if (!(pdptr & PT_PRESENT_MASK)) {
3720                                 vcpu->arch.mmu->pae_root[i] = 0;
3721                                 continue;
3722                         }
3723                         root_gfn = pdptr >> PAGE_SHIFT;
3724                         if (mmu_check_root(vcpu, root_gfn))
3725                                 return 1;
3726                 }
3727                 spin_lock(&vcpu->kvm->mmu_lock);
3728                 if (make_mmu_pages_available(vcpu) < 0) {
3729                         spin_unlock(&vcpu->kvm->mmu_lock);
3730                         return -ENOSPC;
3731                 }
3732                 sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30, PT32_ROOT_LEVEL,
3733                                       0, ACC_ALL);
3734                 root = __pa(sp->spt);
3735                 ++sp->root_count;
3736                 spin_unlock(&vcpu->kvm->mmu_lock);
3737
3738                 vcpu->arch.mmu->pae_root[i] = root | pm_mask;
3739         }
3740         vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3741
3742         /*
3743          * If we shadow a 32 bit page table with a long mode page
3744          * table we enter this path.
3745          */
3746         if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL) {
3747                 if (vcpu->arch.mmu->lm_root == NULL) {
3748                         /*
3749                          * The additional page necessary for this is only
3750                          * allocated on demand.
3751                          */
3752
3753                         u64 *lm_root;
3754
3755                         lm_root = (void*)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3756                         if (lm_root == NULL)
3757                                 return 1;
3758
3759                         lm_root[0] = __pa(vcpu->arch.mmu->pae_root) | pm_mask;
3760
3761                         vcpu->arch.mmu->lm_root = lm_root;
3762                 }
3763
3764                 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->lm_root);
3765         }
3766
3767 set_root_cr3:
3768         vcpu->arch.mmu->root_cr3 = root_cr3;
3769
3770         return 0;
3771 }
3772
3773 static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
3774 {
3775         if (vcpu->arch.mmu->direct_map)
3776                 return mmu_alloc_direct_roots(vcpu);
3777         else
3778                 return mmu_alloc_shadow_roots(vcpu);
3779 }
3780
3781 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3782 {
3783         int i;
3784         struct kvm_mmu_page *sp;
3785
3786         if (vcpu->arch.mmu->direct_map)
3787                 return;
3788
3789         if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3790                 return;
3791
3792         vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
3793
3794         if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3795                 hpa_t root = vcpu->arch.mmu->root_hpa;
3796                 sp = page_header(root);
3797
3798                 /*
3799                  * Even if another CPU was marking the SP as unsync-ed
3800                  * simultaneously, any guest page table changes are not
3801                  * guaranteed to be visible anyway until this VCPU issues a TLB
3802                  * flush strictly after those changes are made. We only need to
3803                  * ensure that the other CPU sets these flags before any actual
3804                  * changes to the page tables are made. The comments in
3805                  * mmu_need_write_protect() describe what could go wrong if this
3806                  * requirement isn't satisfied.
3807                  */
3808                 if (!smp_load_acquire(&sp->unsync) &&
3809                     !smp_load_acquire(&sp->unsync_children))
3810                         return;
3811
3812                 spin_lock(&vcpu->kvm->mmu_lock);
3813                 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3814
3815                 mmu_sync_children(vcpu, sp);
3816
3817                 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3818                 spin_unlock(&vcpu->kvm->mmu_lock);
3819                 return;
3820         }
3821
3822         spin_lock(&vcpu->kvm->mmu_lock);
3823         kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3824
3825         for (i = 0; i < 4; ++i) {
3826                 hpa_t root = vcpu->arch.mmu->pae_root[i];
3827
3828                 if (root && VALID_PAGE(root)) {
3829                         root &= PT64_BASE_ADDR_MASK;
3830                         sp = page_header(root);
3831                         mmu_sync_children(vcpu, sp);
3832                 }
3833         }
3834
3835         kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3836         spin_unlock(&vcpu->kvm->mmu_lock);
3837 }
3838 EXPORT_SYMBOL_GPL(kvm_mmu_sync_roots);
3839
3840 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gva_t vaddr,
3841                                   u32 access, struct x86_exception *exception)
3842 {
3843         if (exception)
3844                 exception->error_code = 0;
3845         return vaddr;
3846 }
3847
3848 static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gva_t vaddr,
3849                                          u32 access,
3850                                          struct x86_exception *exception)
3851 {
3852         if (exception)
3853                 exception->error_code = 0;
3854         return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access, exception);
3855 }
3856
3857 static bool
3858 __is_rsvd_bits_set(struct rsvd_bits_validate *rsvd_check, u64 pte, int level)
3859 {
3860         int bit7 = (pte >> 7) & 1, low6 = pte & 0x3f;
3861
3862         return (pte & rsvd_check->rsvd_bits_mask[bit7][level-1]) |
3863                 ((rsvd_check->bad_mt_xwr & (1ull << low6)) != 0);
3864 }
3865
3866 static bool is_rsvd_bits_set(struct kvm_mmu *mmu, u64 gpte, int level)
3867 {
3868         return __is_rsvd_bits_set(&mmu->guest_rsvd_check, gpte, level);
3869 }
3870
3871 static bool is_shadow_zero_bits_set(struct kvm_mmu *mmu, u64 spte, int level)
3872 {
3873         return __is_rsvd_bits_set(&mmu->shadow_zero_check, spte, level);
3874 }
3875
3876 static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3877 {
3878         /*
3879          * A nested guest cannot use the MMIO cache if it is using nested
3880          * page tables, because cr2 is a nGPA while the cache stores GPAs.
3881          */
3882         if (mmu_is_nested(vcpu))
3883                 return false;
3884
3885         if (direct)
3886                 return vcpu_match_mmio_gpa(vcpu, addr);
3887
3888         return vcpu_match_mmio_gva(vcpu, addr);
3889 }
3890
3891 /* return true if reserved bit is detected on spte. */
3892 static bool
3893 walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
3894 {
3895         struct kvm_shadow_walk_iterator iterator;
3896         u64 sptes[PT64_ROOT_MAX_LEVEL], spte = 0ull;
3897         int root, leaf;
3898         bool reserved = false;
3899
3900         if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3901                 goto exit;
3902
3903         walk_shadow_page_lockless_begin(vcpu);
3904
3905         for (shadow_walk_init(&iterator, vcpu, addr),
3906                  leaf = root = iterator.level;
3907              shadow_walk_okay(&iterator);
3908              __shadow_walk_next(&iterator, spte)) {
3909                 spte = mmu_spte_get_lockless(iterator.sptep);
3910
3911                 sptes[leaf - 1] = spte;
3912                 leaf--;
3913
3914                 if (!is_shadow_present_pte(spte))
3915                         break;
3916
3917                 reserved |= is_shadow_zero_bits_set(vcpu->arch.mmu, spte,
3918                                                     iterator.level);
3919         }
3920
3921         walk_shadow_page_lockless_end(vcpu);
3922
3923         if (reserved) {
3924                 pr_err("%s: detect reserved bits on spte, addr 0x%llx, dump hierarchy:\n",
3925                        __func__, addr);
3926                 while (root > leaf) {
3927                         pr_err("------ spte 0x%llx level %d.\n",
3928                                sptes[root - 1], root);
3929                         root--;
3930                 }
3931         }
3932 exit:
3933         *sptep = spte;
3934         return reserved;
3935 }
3936
3937 static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3938 {
3939         u64 spte;
3940         bool reserved;
3941
3942         if (mmio_info_in_cache(vcpu, addr, direct))
3943                 return RET_PF_EMULATE;
3944
3945         reserved = walk_shadow_page_get_mmio_spte(vcpu, addr, &spte);
3946         if (WARN_ON(reserved))
3947                 return -EINVAL;
3948
3949         if (is_mmio_spte(spte)) {
3950                 gfn_t gfn = get_mmio_spte_gfn(spte);
3951                 unsigned access = get_mmio_spte_access(spte);
3952
3953                 if (!check_mmio_spte(vcpu, spte))
3954                         return RET_PF_INVALID;
3955
3956                 if (direct)
3957                         addr = 0;
3958
3959                 trace_handle_mmio_page_fault(addr, gfn, access);
3960                 vcpu_cache_mmio_info(vcpu, addr, gfn, access);
3961                 return RET_PF_EMULATE;
3962         }
3963
3964         /*
3965          * If the page table is zapped by other cpus, let CPU fault again on
3966          * the address.
3967          */
3968         return RET_PF_RETRY;
3969 }
3970
3971 static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
3972                                          u32 error_code, gfn_t gfn)
3973 {
3974         if (unlikely(error_code & PFERR_RSVD_MASK))
3975                 return false;
3976
3977         if (!(error_code & PFERR_PRESENT_MASK) ||
3978               !(error_code & PFERR_WRITE_MASK))
3979                 return false;
3980
3981         /*
3982          * guest is writing the page which is write tracked which can
3983          * not be fixed by page fault handler.
3984          */
3985         if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
3986                 return true;
3987
3988         return false;
3989 }
3990
3991 static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
3992 {
3993         struct kvm_shadow_walk_iterator iterator;
3994         u64 spte;
3995
3996         if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3997                 return;
3998
3999         walk_shadow_page_lockless_begin(vcpu);
4000         for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) {
4001                 clear_sp_write_flooding_count(iterator.sptep);
4002                 if (!is_shadow_present_pte(spte))
4003                         break;
4004         }
4005         walk_shadow_page_lockless_end(vcpu);
4006 }
4007
4008 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
4009                                 u32 error_code, bool prefault)
4010 {
4011         gfn_t gfn = gva >> PAGE_SHIFT;
4012         int r;
4013
4014         pgprintk("%s: gva %lx error %x\n", __func__, gva, error_code);
4015
4016         if (page_fault_handle_page_track(vcpu, error_code, gfn))
4017                 return RET_PF_EMULATE;
4018
4019         r = mmu_topup_memory_caches(vcpu);
4020         if (r)
4021                 return r;
4022
4023         MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa));
4024
4025
4026         return nonpaging_map(vcpu, gva & PAGE_MASK,
4027                              error_code, gfn, prefault);
4028 }
4029
4030 static int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn)
4031 {
4032         struct kvm_arch_async_pf arch;
4033
4034         arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
4035         arch.gfn = gfn;
4036         arch.direct_map = vcpu->arch.mmu->direct_map;
4037         arch.cr3 = vcpu->arch.mmu->get_cr3(vcpu);
4038
4039         return kvm_setup_async_pf(vcpu, gva, kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
4040 }
4041
4042 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
4043                          gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable)
4044 {
4045         struct kvm_memory_slot *slot;
4046         bool async;
4047
4048         /*
4049          * Don't expose private memslots to L2.
4050          */
4051         if (is_guest_mode(vcpu) && !kvm_is_visible_gfn(vcpu->kvm, gfn)) {
4052                 *pfn = KVM_PFN_NOSLOT;
4053                 return false;
4054         }
4055
4056         slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
4057         async = false;
4058         *pfn = __gfn_to_pfn_memslot(slot, gfn, false, &async, write, writable);
4059         if (!async)
4060                 return false; /* *pfn has correct page already */
4061
4062         if (!prefault && kvm_can_do_async_pf(vcpu)) {
4063                 trace_kvm_try_async_get_page(gva, gfn);
4064                 if (kvm_find_async_pf_gfn(vcpu, gfn)) {
4065                         trace_kvm_async_pf_doublefault(gva, gfn);
4066                         kvm_make_request(KVM_REQ_APF_HALT, vcpu);
4067                         return true;
4068                 } else if (kvm_arch_setup_async_pf(vcpu, gva, gfn))
4069                         return true;
4070         }
4071
4072         *pfn = __gfn_to_pfn_memslot(slot, gfn, false, NULL, write, writable);
4073         return false;
4074 }
4075
4076 int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4077                                 u64 fault_address, char *insn, int insn_len)
4078 {
4079         int r = 1;
4080
4081         vcpu->arch.l1tf_flush_l1d = true;
4082         switch (vcpu->arch.apf.host_apf_reason) {
4083         default:
4084                 trace_kvm_page_fault(fault_address, error_code);
4085
4086                 if (kvm_event_needs_reinjection(vcpu))
4087                         kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4088                 r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4089                                 insn_len);
4090                 break;
4091         case KVM_PV_REASON_PAGE_NOT_PRESENT:
4092                 vcpu->arch.apf.host_apf_reason = 0;
4093                 local_irq_disable();
4094                 kvm_async_pf_task_wait(fault_address, 0);
4095                 local_irq_enable();
4096                 break;
4097         case KVM_PV_REASON_PAGE_READY:
4098                 vcpu->arch.apf.host_apf_reason = 0;
4099                 local_irq_disable();
4100                 kvm_async_pf_task_wake(fault_address);
4101                 local_irq_enable();
4102                 break;
4103         }
4104         return r;
4105 }
4106 EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4107
4108 static bool
4109 check_hugepage_cache_consistency(struct kvm_vcpu *vcpu, gfn_t gfn, int level)
4110 {
4111         int page_num = KVM_PAGES_PER_HPAGE(level);
4112
4113         gfn &= ~(page_num - 1);
4114
4115         return kvm_mtrr_check_gfn_range_consistency(vcpu, gfn, page_num);
4116 }
4117
4118 static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa, u32 error_code,
4119                           bool prefault)
4120 {
4121         kvm_pfn_t pfn;
4122         int r;
4123         int level;
4124         bool force_pt_level;
4125         gfn_t gfn = gpa >> PAGE_SHIFT;
4126         unsigned long mmu_seq;
4127         int write = error_code & PFERR_WRITE_MASK;
4128         bool map_writable;
4129
4130         MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa));
4131
4132         if (page_fault_handle_page_track(vcpu, error_code, gfn))
4133                 return RET_PF_EMULATE;
4134
4135         r = mmu_topup_memory_caches(vcpu);
4136         if (r)
4137                 return r;
4138
4139         force_pt_level = !check_hugepage_cache_consistency(vcpu, gfn,
4140                                                            PT_DIRECTORY_LEVEL);
4141         level = mapping_level(vcpu, gfn, &force_pt_level);
4142         if (likely(!force_pt_level)) {
4143                 if (level > PT_DIRECTORY_LEVEL &&
4144                     !check_hugepage_cache_consistency(vcpu, gfn, level))
4145                         level = PT_DIRECTORY_LEVEL;
4146                 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
4147         }
4148
4149         if (fast_page_fault(vcpu, gpa, level, error_code))
4150                 return RET_PF_RETRY;
4151
4152         mmu_seq = vcpu->kvm->mmu_notifier_seq;
4153         smp_rmb();
4154
4155         if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
4156                 return RET_PF_RETRY;
4157
4158         if (handle_abnormal_pfn(vcpu, 0, gfn, pfn, ACC_ALL, &r))
4159                 return r;
4160
4161         r = RET_PF_RETRY;
4162         spin_lock(&vcpu->kvm->mmu_lock);
4163         if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
4164                 goto out_unlock;
4165         if (make_mmu_pages_available(vcpu) < 0)
4166                 goto out_unlock;
4167         if (likely(!force_pt_level))
4168                 transparent_hugepage_adjust(vcpu, gfn, &pfn, &level);
4169         r = __direct_map(vcpu, gpa, write, map_writable, level, pfn, prefault);
4170 out_unlock:
4171         spin_unlock(&vcpu->kvm->mmu_lock);
4172         kvm_release_pfn_clean(pfn);
4173         return r;
4174 }
4175
4176 static void nonpaging_init_context(struct kvm_vcpu *vcpu,
4177                                    struct kvm_mmu *context)
4178 {
4179         context->page_fault = nonpaging_page_fault;
4180         context->gva_to_gpa = nonpaging_gva_to_gpa;
4181         context->sync_page = nonpaging_sync_page;
4182         context->invlpg = nonpaging_invlpg;
4183         context->update_pte = nonpaging_update_pte;
4184         context->root_level = 0;
4185         context->shadow_root_level = PT32E_ROOT_LEVEL;
4186         context->direct_map = true;
4187         context->nx = false;
4188 }
4189
4190 /*
4191  * Find out if a previously cached root matching the new CR3/role is available.
4192  * The current root is also inserted into the cache.
4193  * If a matching root was found, it is assigned to kvm_mmu->root_hpa and true is
4194  * returned.
4195  * Otherwise, the LRU root from the cache is assigned to kvm_mmu->root_hpa and
4196  * false is returned. This root should now be freed by the caller.
4197  */
4198 static bool cached_root_available(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4199                                   union kvm_mmu_page_role new_role)
4200 {
4201         uint i;
4202         struct kvm_mmu_root_info root;
4203         struct kvm_mmu *mmu = vcpu->arch.mmu;
4204
4205         root.cr3 = mmu->root_cr3;
4206         root.hpa = mmu->root_hpa;
4207
4208         for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
4209                 swap(root, mmu->prev_roots[i]);
4210
4211                 if (new_cr3 == root.cr3 && VALID_PAGE(root.hpa) &&
4212                     page_header(root.hpa) != NULL &&
4213                     new_role.word == page_header(root.hpa)->role.word)
4214                         break;
4215         }
4216
4217         mmu->root_hpa = root.hpa;
4218         mmu->root_cr3 = root.cr3;
4219
4220         return i < KVM_MMU_NUM_PREV_ROOTS;
4221 }
4222
4223 static bool fast_cr3_switch(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4224                             union kvm_mmu_page_role new_role,
4225                             bool skip_tlb_flush)
4226 {
4227         struct kvm_mmu *mmu = vcpu->arch.mmu;
4228
4229         /*
4230          * For now, limit the fast switch to 64-bit hosts+VMs in order to avoid
4231          * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
4232          * later if necessary.
4233          */
4234         if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
4235             mmu->root_level >= PT64_ROOT_4LEVEL) {
4236                 if (mmu_check_root(vcpu, new_cr3 >> PAGE_SHIFT))
4237                         return false;
4238
4239                 if (cached_root_available(vcpu, new_cr3, new_role)) {
4240                         kvm_make_request(KVM_REQ_LOAD_CR3, vcpu);
4241                         if (!skip_tlb_flush) {
4242                                 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4243                                 kvm_x86_ops->tlb_flush(vcpu, true);
4244                         }
4245
4246                         /*
4247                          * The last MMIO access's GVA and GPA are cached in the
4248                          * VCPU. When switching to a new CR3, that GVA->GPA
4249                          * mapping may no longer be valid. So clear any cached
4250                          * MMIO info even when we don't need to sync the shadow
4251                          * page tables.
4252                          */
4253                         vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4254
4255                         __clear_sp_write_flooding_count(
4256                                 page_header(mmu->root_hpa));
4257
4258                         return true;
4259                 }
4260         }
4261
4262         return false;
4263 }
4264
4265 static void __kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4266                               union kvm_mmu_page_role new_role,
4267                               bool skip_tlb_flush)
4268 {
4269         if (!fast_cr3_switch(vcpu, new_cr3, new_role, skip_tlb_flush))
4270                 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu,
4271                                    KVM_MMU_ROOT_CURRENT);
4272 }
4273
4274 void kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3, bool skip_tlb_flush)
4275 {
4276         __kvm_mmu_new_cr3(vcpu, new_cr3, kvm_mmu_calc_root_page_role(vcpu),
4277                           skip_tlb_flush);
4278 }
4279 EXPORT_SYMBOL_GPL(kvm_mmu_new_cr3);
4280
4281 static unsigned long get_cr3(struct kvm_vcpu *vcpu)
4282 {
4283         return kvm_read_cr3(vcpu);
4284 }
4285
4286 static void inject_page_fault(struct kvm_vcpu *vcpu,
4287                               struct x86_exception *fault)
4288 {
4289         vcpu->arch.mmu->inject_page_fault(vcpu, fault);
4290 }
4291
4292 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4293                            unsigned access, int *nr_present)
4294 {
4295         if (unlikely(is_mmio_spte(*sptep))) {
4296                 if (gfn != get_mmio_spte_gfn(*sptep)) {
4297                         mmu_spte_clear_no_track(sptep);
4298                         return true;
4299                 }
4300
4301                 (*nr_present)++;
4302                 mark_mmio_spte(vcpu, sptep, gfn, access);
4303                 return true;
4304         }
4305
4306         return false;
4307 }
4308
4309 static inline bool is_last_gpte(struct kvm_mmu *mmu,
4310                                 unsigned level, unsigned gpte)
4311 {
4312         /*
4313          * The RHS has bit 7 set iff level < mmu->last_nonleaf_level.
4314          * If it is clear, there are no large pages at this level, so clear
4315          * PT_PAGE_SIZE_MASK in gpte if that is the case.
4316          */
4317         gpte &= level - mmu->last_nonleaf_level;
4318
4319         /*
4320          * PT_PAGE_TABLE_LEVEL always terminates.  The RHS has bit 7 set
4321          * iff level <= PT_PAGE_TABLE_LEVEL, which for our purpose means
4322          * level == PT_PAGE_TABLE_LEVEL; set PT_PAGE_SIZE_MASK in gpte then.
4323          */
4324         gpte |= level - PT_PAGE_TABLE_LEVEL - 1;
4325
4326         return gpte & PT_PAGE_SIZE_MASK;
4327 }
4328
4329 #define PTTYPE_EPT 18 /* arbitrary */
4330 #define PTTYPE PTTYPE_EPT
4331 #include "paging_tmpl.h"
4332 #undef PTTYPE
4333
4334 #define PTTYPE 64
4335 #include "paging_tmpl.h"
4336 #undef PTTYPE
4337
4338 #define PTTYPE 32
4339 #include "paging_tmpl.h"
4340 #undef PTTYPE
4341
4342 static void
4343 __reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4344                         struct rsvd_bits_validate *rsvd_check,
4345                         int maxphyaddr, int level, bool nx, bool gbpages,
4346                         bool pse, bool amd)
4347 {
4348         u64 exb_bit_rsvd = 0;
4349         u64 gbpages_bit_rsvd = 0;
4350         u64 nonleaf_bit8_rsvd = 0;
4351
4352         rsvd_check->bad_mt_xwr = 0;
4353
4354         if (!nx)
4355                 exb_bit_rsvd = rsvd_bits(63, 63);
4356         if (!gbpages)
4357                 gbpages_bit_rsvd = rsvd_bits(7, 7);
4358
4359         /*
4360          * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4361          * leaf entries) on AMD CPUs only.
4362          */
4363         if (amd)
4364                 nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4365
4366         switch (level) {
4367         case PT32_ROOT_LEVEL:
4368                 /* no rsvd bits for 2 level 4K page table entries */
4369                 rsvd_check->rsvd_bits_mask[0][1] = 0;
4370                 rsvd_check->rsvd_bits_mask[0][0] = 0;
4371                 rsvd_check->rsvd_bits_mask[1][0] =
4372                         rsvd_check->rsvd_bits_mask[0][0];
4373
4374                 if (!pse) {
4375                         rsvd_check->rsvd_bits_mask[1][1] = 0;
4376                         break;
4377                 }
4378
4379                 if (is_cpuid_PSE36())
4380                         /* 36bits PSE 4MB page */
4381                         rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4382                 else
4383                         /* 32 bits PSE 4MB page */
4384                         rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4385                 break;
4386         case PT32E_ROOT_LEVEL:
4387                 rsvd_check->rsvd_bits_mask[0][2] =
4388                         rsvd_bits(maxphyaddr, 63) |
4389                         rsvd_bits(5, 8) | rsvd_bits(1, 2);      /* PDPTE */
4390                 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4391                         rsvd_bits(maxphyaddr, 62);      /* PDE */
4392                 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4393                         rsvd_bits(maxphyaddr, 62);      /* PTE */
4394                 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4395                         rsvd_bits(maxphyaddr, 62) |
4396                         rsvd_bits(13, 20);              /* large page */
4397                 rsvd_check->rsvd_bits_mask[1][0] =
4398                         rsvd_check->rsvd_bits_mask[0][0];
4399                 break;
4400         case PT64_ROOT_5LEVEL:
4401                 rsvd_check->rsvd_bits_mask[0][4] = exb_bit_rsvd |
4402                         nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4403                         rsvd_bits(maxphyaddr, 51);
4404                 rsvd_check->rsvd_bits_mask[1][4] =
4405                         rsvd_check->rsvd_bits_mask[0][4];
4406                 /* fall through */
4407         case PT64_ROOT_4LEVEL:
4408                 rsvd_check->rsvd_bits_mask[0][3] = exb_bit_rsvd |
4409                         nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4410                         rsvd_bits(maxphyaddr, 51);
4411                 rsvd_check->rsvd_bits_mask[0][2] = exb_bit_rsvd |
4412                         nonleaf_bit8_rsvd | gbpages_bit_rsvd |
4413                         rsvd_bits(maxphyaddr, 51);
4414                 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4415                         rsvd_bits(maxphyaddr, 51);
4416                 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4417                         rsvd_bits(maxphyaddr, 51);
4418                 rsvd_check->rsvd_bits_mask[1][3] =
4419                         rsvd_check->rsvd_bits_mask[0][3];
4420                 rsvd_check->rsvd_bits_mask[1][2] = exb_bit_rsvd |
4421                         gbpages_bit_rsvd | rsvd_bits(maxphyaddr, 51) |
4422                         rsvd_bits(13, 29);
4423                 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4424                         rsvd_bits(maxphyaddr, 51) |
4425                         rsvd_bits(13, 20);              /* large page */
4426                 rsvd_check->rsvd_bits_mask[1][0] =
4427                         rsvd_check->rsvd_bits_mask[0][0];
4428                 break;
4429         }
4430 }
4431
4432 static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4433                                   struct kvm_mmu *context)
4434 {
4435         __reset_rsvds_bits_mask(vcpu, &context->guest_rsvd_check,
4436                                 cpuid_maxphyaddr(vcpu), context->root_level,
4437                                 context->nx,
4438                                 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4439                                 is_pse(vcpu), guest_cpuid_is_amd(vcpu));
4440 }
4441
4442 static void
4443 __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
4444                             int maxphyaddr, bool execonly)
4445 {
4446         u64 bad_mt_xwr;
4447
4448         rsvd_check->rsvd_bits_mask[0][4] =
4449                 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4450         rsvd_check->rsvd_bits_mask[0][3] =
4451                 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4452         rsvd_check->rsvd_bits_mask[0][2] =
4453                 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4454         rsvd_check->rsvd_bits_mask[0][1] =
4455                 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4456         rsvd_check->rsvd_bits_mask[0][0] = rsvd_bits(maxphyaddr, 51);
4457
4458         /* large page */
4459         rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4460         rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
4461         rsvd_check->rsvd_bits_mask[1][2] =
4462                 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 29);
4463         rsvd_check->rsvd_bits_mask[1][1] =
4464                 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 20);
4465         rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4466
4467         bad_mt_xwr = 0xFFull << (2 * 8);        /* bits 3..5 must not be 2 */
4468         bad_mt_xwr |= 0xFFull << (3 * 8);       /* bits 3..5 must not be 3 */
4469         bad_mt_xwr |= 0xFFull << (7 * 8);       /* bits 3..5 must not be 7 */
4470         bad_mt_xwr |= REPEAT_BYTE(1ull << 2);   /* bits 0..2 must not be 010 */
4471         bad_mt_xwr |= REPEAT_BYTE(1ull << 6);   /* bits 0..2 must not be 110 */
4472         if (!execonly) {
4473                 /* bits 0..2 must not be 100 unless VMX capabilities allow it */
4474                 bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4475         }
4476         rsvd_check->bad_mt_xwr = bad_mt_xwr;
4477 }
4478
4479 static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
4480                 struct kvm_mmu *context, bool execonly)
4481 {
4482         __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
4483                                     cpuid_maxphyaddr(vcpu), execonly);
4484 }
4485
4486 /*
4487  * the page table on host is the shadow page table for the page
4488  * table in guest or amd nested guest, its mmu features completely
4489  * follow the features in guest.
4490  */
4491 void
4492 reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
4493 {
4494         bool uses_nx = context->nx ||
4495                 context->mmu_role.base.smep_andnot_wp;
4496         struct rsvd_bits_validate *shadow_zero_check;
4497         int i;
4498
4499         /*
4500          * Passing "true" to the last argument is okay; it adds a check
4501          * on bit 8 of the SPTEs which KVM doesn't use anyway.
4502          */
4503         shadow_zero_check = &context->shadow_zero_check;
4504         __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4505                                 shadow_phys_bits,
4506                                 context->shadow_root_level, uses_nx,
4507                                 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4508                                 is_pse(vcpu), true);
4509
4510         if (!shadow_me_mask)
4511                 return;
4512
4513         for (i = context->shadow_root_level; --i >= 0;) {
4514                 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4515                 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4516         }
4517
4518 }
4519 EXPORT_SYMBOL_GPL(reset_shadow_zero_bits_mask);
4520
4521 static inline bool boot_cpu_is_amd(void)
4522 {
4523         WARN_ON_ONCE(!tdp_enabled);
4524         return shadow_x_mask == 0;
4525 }
4526
4527 /*
4528  * the direct page table on host, use as much mmu features as
4529  * possible, however, kvm currently does not do execution-protection.
4530  */
4531 static void
4532 reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4533                                 struct kvm_mmu *context)
4534 {
4535         struct rsvd_bits_validate *shadow_zero_check;
4536         int i;
4537
4538         shadow_zero_check = &context->shadow_zero_check;
4539
4540         if (boot_cpu_is_amd())
4541                 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4542                                         shadow_phys_bits,
4543                                         context->shadow_root_level, false,
4544                                         boot_cpu_has(X86_FEATURE_GBPAGES),
4545                                         true, true);
4546         else
4547                 __reset_rsvds_bits_mask_ept(shadow_zero_check,
4548                                             shadow_phys_bits,
4549                                             false);
4550
4551         if (!shadow_me_mask)
4552                 return;
4553
4554         for (i = context->shadow_root_level; --i >= 0;) {
4555                 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4556                 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4557         }
4558 }
4559
4560 /*
4561  * as the comments in reset_shadow_zero_bits_mask() except it
4562  * is the shadow page table for intel nested guest.
4563  */
4564 static void
4565 reset_ept_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4566                                 struct kvm_mmu *context, bool execonly)
4567 {
4568         __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
4569                                     shadow_phys_bits, execonly);
4570 }
4571
4572 #define BYTE_MASK(access) \
4573         ((1 & (access) ? 2 : 0) | \
4574          (2 & (access) ? 4 : 0) | \
4575          (3 & (access) ? 8 : 0) | \
4576          (4 & (access) ? 16 : 0) | \
4577          (5 & (access) ? 32 : 0) | \
4578          (6 & (access) ? 64 : 0) | \
4579          (7 & (access) ? 128 : 0))
4580
4581
4582 static void update_permission_bitmask(struct kvm_vcpu *vcpu,
4583                                       struct kvm_mmu *mmu, bool ept)
4584 {
4585         unsigned byte;
4586
4587         const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4588         const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4589         const u8 u = BYTE_MASK(ACC_USER_MASK);
4590
4591         bool cr4_smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP) != 0;
4592         bool cr4_smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP) != 0;
4593         bool cr0_wp = is_write_protection(vcpu);
4594
4595         for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
4596                 unsigned pfec = byte << 1;
4597
4598                 /*
4599                  * Each "*f" variable has a 1 bit for each UWX value
4600                  * that causes a fault with the given PFEC.
4601                  */
4602
4603                 /* Faults from writes to non-writable pages */
4604                 u8 wf = (pfec & PFERR_WRITE_MASK) ? ~w : 0;
4605                 /* Faults from user mode accesses to supervisor pages */
4606                 u8 uf = (pfec & PFERR_USER_MASK) ? ~u : 0;
4607                 /* Faults from fetches of non-executable pages*/
4608                 u8 ff = (pfec & PFERR_FETCH_MASK) ? ~x : 0;
4609                 /* Faults from kernel mode fetches of user pages */
4610                 u8 smepf = 0;
4611                 /* Faults from kernel mode accesses of user pages */
4612                 u8 smapf = 0;
4613
4614                 if (!ept) {
4615                         /* Faults from kernel mode accesses to user pages */
4616                         u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
4617
4618                         /* Not really needed: !nx will cause pte.nx to fault */
4619                         if (!mmu->nx)
4620                                 ff = 0;
4621
4622                         /* Allow supervisor writes if !cr0.wp */
4623                         if (!cr0_wp)
4624                                 wf = (pfec & PFERR_USER_MASK) ? wf : 0;
4625
4626                         /* Disallow supervisor fetches of user code if cr4.smep */
4627                         if (cr4_smep)
4628                                 smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
4629
4630                         /*
4631                          * SMAP:kernel-mode data accesses from user-mode
4632                          * mappings should fault. A fault is considered
4633                          * as a SMAP violation if all of the following
4634                          * conditions are true:
4635                          *   - X86_CR4_SMAP is set in CR4
4636                          *   - A user page is accessed
4637                          *   - The access is not a fetch
4638                          *   - Page fault in kernel mode
4639                          *   - if CPL = 3 or X86_EFLAGS_AC is clear
4640                          *
4641                          * Here, we cover the first three conditions.
4642                          * The fourth is computed dynamically in permission_fault();
4643                          * PFERR_RSVD_MASK bit will be set in PFEC if the access is
4644                          * *not* subject to SMAP restrictions.
4645                          */
4646                         if (cr4_smap)
4647                                 smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
4648                 }
4649
4650                 mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
4651         }
4652 }
4653
4654 /*
4655 * PKU is an additional mechanism by which the paging controls access to
4656 * user-mode addresses based on the value in the PKRU register.  Protection
4657 * key violations are reported through a bit in the page fault error code.
4658 * Unlike other bits of the error code, the PK bit is not known at the
4659 * call site of e.g. gva_to_gpa; it must be computed directly in
4660 * permission_fault based on two bits of PKRU, on some machine state (CR4,
4661 * CR0, EFER, CPL), and on other bits of the error code and the page tables.
4662 *
4663 * In particular the following conditions come from the error code, the
4664 * page tables and the machine state:
4665 * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
4666 * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
4667 * - PK is always zero if U=0 in the page tables
4668 * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
4669 *
4670 * The PKRU bitmask caches the result of these four conditions.  The error
4671 * code (minus the P bit) and the page table's U bit form an index into the
4672 * PKRU bitmask.  Two bits of the PKRU bitmask are then extracted and ANDed
4673 * with the two bits of the PKRU register corresponding to the protection key.
4674 * For the first three conditions above the bits will be 00, thus masking
4675 * away both AD and WD.  For all reads or if the last condition holds, WD
4676 * only will be masked away.
4677 */
4678 static void update_pkru_bitmask(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
4679                                 bool ept)
4680 {
4681         unsigned bit;
4682         bool wp;
4683
4684         if (ept) {
4685                 mmu->pkru_mask = 0;
4686                 return;
4687         }
4688
4689         /* PKEY is enabled only if CR4.PKE and EFER.LMA are both set. */
4690         if (!kvm_read_cr4_bits(vcpu, X86_CR4_PKE) || !is_long_mode(vcpu)) {
4691                 mmu->pkru_mask = 0;
4692                 return;
4693         }
4694
4695         wp = is_write_protection(vcpu);
4696
4697         for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
4698                 unsigned pfec, pkey_bits;
4699                 bool check_pkey, check_write, ff, uf, wf, pte_user;
4700
4701                 pfec = bit << 1;
4702                 ff = pfec & PFERR_FETCH_MASK;
4703                 uf = pfec & PFERR_USER_MASK;
4704                 wf = pfec & PFERR_WRITE_MASK;
4705
4706                 /* PFEC.RSVD is replaced by ACC_USER_MASK. */
4707                 pte_user = pfec & PFERR_RSVD_MASK;
4708
4709                 /*
4710                  * Only need to check the access which is not an
4711                  * instruction fetch and is to a user page.
4712                  */
4713                 check_pkey = (!ff && pte_user);
4714                 /*
4715                  * write access is controlled by PKRU if it is a
4716                  * user access or CR0.WP = 1.
4717                  */
4718                 check_write = check_pkey && wf && (uf || wp);
4719
4720                 /* PKRU.AD stops both read and write access. */
4721                 pkey_bits = !!check_pkey;
4722                 /* PKRU.WD stops write access. */
4723                 pkey_bits |= (!!check_write) << 1;
4724
4725                 mmu->pkru_mask |= (pkey_bits & 3) << pfec;
4726         }
4727 }
4728
4729 static void update_last_nonleaf_level(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
4730 {
4731         unsigned root_level = mmu->root_level;
4732
4733         mmu->last_nonleaf_level = root_level;
4734         if (root_level == PT32_ROOT_LEVEL && is_pse(vcpu))
4735                 mmu->last_nonleaf_level++;
4736 }
4737
4738 static void paging64_init_context_common(struct kvm_vcpu *vcpu,
4739                                          struct kvm_mmu *context,
4740                                          int level)
4741 {
4742         context->nx = is_nx(vcpu);
4743         context->root_level = level;
4744
4745         reset_rsvds_bits_mask(vcpu, context);
4746         update_permission_bitmask(vcpu, context, false);
4747         update_pkru_bitmask(vcpu, context, false);
4748         update_last_nonleaf_level(vcpu, context);
4749
4750         MMU_WARN_ON(!is_pae(vcpu));
4751         context->page_fault = paging64_page_fault;
4752         context->gva_to_gpa = paging64_gva_to_gpa;
4753         context->sync_page = paging64_sync_page;
4754         context->invlpg = paging64_invlpg;
4755         context->update_pte = paging64_update_pte;
4756         context->shadow_root_level = level;
4757         context->direct_map = false;
4758 }
4759
4760 static void paging64_init_context(struct kvm_vcpu *vcpu,
4761                                   struct kvm_mmu *context)
4762 {
4763         int root_level = is_la57_mode(vcpu) ?
4764                          PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4765
4766         paging64_init_context_common(vcpu, context, root_level);
4767 }
4768
4769 static void paging32_init_context(struct kvm_vcpu *vcpu,
4770                                   struct kvm_mmu *context)
4771 {
4772         context->nx = false;
4773         context->root_level = PT32_ROOT_LEVEL;
4774
4775         reset_rsvds_bits_mask(vcpu, context);
4776         update_permission_bitmask(vcpu, context, false);
4777         update_pkru_bitmask(vcpu, context, false);
4778         update_last_nonleaf_level(vcpu, context);
4779
4780         context->page_fault = paging32_page_fault;
4781         context->gva_to_gpa = paging32_gva_to_gpa;
4782         context->sync_page = paging32_sync_page;
4783         context->invlpg = paging32_invlpg;
4784         context->update_pte = paging32_update_pte;
4785         context->shadow_root_level = PT32E_ROOT_LEVEL;
4786         context->direct_map = false;
4787 }
4788
4789 static void paging32E_init_context(struct kvm_vcpu *vcpu,
4790                                    struct kvm_mmu *context)
4791 {
4792         paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
4793 }
4794
4795 static union kvm_mmu_extended_role kvm_calc_mmu_role_ext(struct kvm_vcpu *vcpu)
4796 {
4797         union kvm_mmu_extended_role ext = {0};
4798
4799         ext.cr0_pg = !!is_paging(vcpu);
4800         ext.cr4_pae = !!is_pae(vcpu);
4801         ext.cr4_smep = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
4802         ext.cr4_smap = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
4803         ext.cr4_pse = !!is_pse(vcpu);
4804         ext.cr4_pke = !!kvm_read_cr4_bits(vcpu, X86_CR4_PKE);
4805         ext.cr4_la57 = !!kvm_read_cr4_bits(vcpu, X86_CR4_LA57);
4806         ext.maxphyaddr = cpuid_maxphyaddr(vcpu);
4807
4808         ext.valid = 1;
4809
4810         return ext;
4811 }
4812
4813 static union kvm_mmu_role kvm_calc_mmu_role_common(struct kvm_vcpu *vcpu,
4814                                                    bool base_only)
4815 {
4816         union kvm_mmu_role role = {0};
4817
4818         role.base.access = ACC_ALL;
4819         role.base.nxe = !!is_nx(vcpu);
4820         role.base.cr0_wp = is_write_protection(vcpu);
4821         role.base.smm = is_smm(vcpu);
4822         role.base.guest_mode = is_guest_mode(vcpu);
4823
4824         if (base_only)
4825                 return role;
4826
4827         role.ext = kvm_calc_mmu_role_ext(vcpu);
4828
4829         return role;
4830 }
4831
4832 static union kvm_mmu_role
4833 kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4834 {
4835         union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4836
4837         role.base.ad_disabled = (shadow_accessed_mask == 0);
4838         role.base.level = kvm_x86_ops->get_tdp_level(vcpu);
4839         role.base.direct = true;
4840         role.base.gpte_is_8_bytes = true;
4841
4842         return role;
4843 }
4844
4845 static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
4846 {
4847         struct kvm_mmu *context = vcpu->arch.mmu;
4848         union kvm_mmu_role new_role =
4849                 kvm_calc_tdp_mmu_root_page_role(vcpu, false);
4850
4851         new_role.base.word &= mmu_base_role_mask.word;
4852         if (new_role.as_u64 == context->mmu_role.as_u64)
4853                 return;
4854
4855         context->mmu_role.as_u64 = new_role.as_u64;
4856         context->page_fault = tdp_page_fault;
4857         context->sync_page = nonpaging_sync_page;
4858         context->invlpg = nonpaging_invlpg;
4859         context->update_pte = nonpaging_update_pte;
4860         context->shadow_root_level = kvm_x86_ops->get_tdp_level(vcpu);
4861         context->direct_map = true;
4862         context->set_cr3 = kvm_x86_ops->set_tdp_cr3;
4863         context->get_cr3 = get_cr3;
4864         context->get_pdptr = kvm_pdptr_read;
4865         context->inject_page_fault = kvm_inject_page_fault;
4866
4867         if (!is_paging(vcpu)) {
4868                 context->nx = false;
4869                 context->gva_to_gpa = nonpaging_gva_to_gpa;
4870                 context->root_level = 0;
4871         } else if (is_long_mode(vcpu)) {
4872                 context->nx = is_nx(vcpu);
4873                 context->root_level = is_la57_mode(vcpu) ?
4874                                 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4875                 reset_rsvds_bits_mask(vcpu, context);
4876                 context->gva_to_gpa = paging64_gva_to_gpa;
4877         } else if (is_pae(vcpu)) {
4878                 context->nx = is_nx(vcpu);
4879                 context->root_level = PT32E_ROOT_LEVEL;
4880                 reset_rsvds_bits_mask(vcpu, context);
4881                 context->gva_to_gpa = paging64_gva_to_gpa;
4882         } else {
4883                 context->nx = false;
4884                 context->root_level = PT32_ROOT_LEVEL;
4885                 reset_rsvds_bits_mask(vcpu, context);
4886                 context->gva_to_gpa = paging32_gva_to_gpa;
4887         }
4888
4889         update_permission_bitmask(vcpu, context, false);
4890         update_pkru_bitmask(vcpu, context, false);
4891         update_last_nonleaf_level(vcpu, context);
4892         reset_tdp_shadow_zero_bits_mask(vcpu, context);
4893 }
4894
4895 static union kvm_mmu_role
4896 kvm_calc_shadow_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4897 {
4898         union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4899
4900         role.base.smep_andnot_wp = role.ext.cr4_smep &&
4901                 !is_write_protection(vcpu);
4902         role.base.smap_andnot_wp = role.ext.cr4_smap &&
4903                 !is_write_protection(vcpu);
4904         role.base.direct = !is_paging(vcpu);
4905         role.base.gpte_is_8_bytes = !!is_pae(vcpu);
4906
4907         if (!is_long_mode(vcpu))
4908                 role.base.level = PT32E_ROOT_LEVEL;
4909         else if (is_la57_mode(vcpu))
4910                 role.base.level = PT64_ROOT_5LEVEL;
4911         else
4912                 role.base.level = PT64_ROOT_4LEVEL;
4913
4914         return role;
4915 }
4916
4917 void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu)
4918 {
4919         struct kvm_mmu *context = vcpu->arch.mmu;
4920         union kvm_mmu_role new_role =
4921                 kvm_calc_shadow_mmu_root_page_role(vcpu, false);
4922
4923         new_role.base.word &= mmu_base_role_mask.word;
4924         if (new_role.as_u64 == context->mmu_role.as_u64)
4925                 return;
4926
4927         if (!is_paging(vcpu))
4928                 nonpaging_init_context(vcpu, context);
4929         else if (is_long_mode(vcpu))
4930                 paging64_init_context(vcpu, context);
4931         else if (is_pae(vcpu))
4932                 paging32E_init_context(vcpu, context);
4933         else
4934                 paging32_init_context(vcpu, context);
4935
4936         context->mmu_role.as_u64 = new_role.as_u64;
4937         reset_shadow_zero_bits_mask(vcpu, context);
4938 }
4939 EXPORT_SYMBOL_GPL(kvm_init_shadow_mmu);
4940
4941 static union kvm_mmu_role
4942 kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
4943                                    bool execonly)
4944 {
4945         union kvm_mmu_role role = {0};
4946
4947         /* SMM flag is inherited from root_mmu */
4948         role.base.smm = vcpu->arch.root_mmu.mmu_role.base.smm;
4949
4950         role.base.level = PT64_ROOT_4LEVEL;
4951         role.base.gpte_is_8_bytes = true;
4952         role.base.direct = false;
4953         role.base.ad_disabled = !accessed_dirty;
4954         role.base.guest_mode = true;
4955         role.base.access = ACC_ALL;
4956
4957         /*
4958          * WP=1 and NOT_WP=1 is an impossible combination, use WP and the
4959          * SMAP variation to denote shadow EPT entries.
4960          */
4961         role.base.cr0_wp = true;
4962         role.base.smap_andnot_wp = true;
4963
4964         role.ext = kvm_calc_mmu_role_ext(vcpu);
4965         role.ext.execonly = execonly;
4966
4967         return role;
4968 }
4969
4970 void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
4971                              bool accessed_dirty, gpa_t new_eptp)
4972 {
4973         struct kvm_mmu *context = vcpu->arch.mmu;
4974         union kvm_mmu_role new_role =
4975                 kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
4976                                                    execonly);
4977
4978         __kvm_mmu_new_cr3(vcpu, new_eptp, new_role.base, false);
4979
4980         new_role.base.word &= mmu_base_role_mask.word;
4981         if (new_role.as_u64 == context->mmu_role.as_u64)
4982                 return;
4983
4984         context->shadow_root_level = PT64_ROOT_4LEVEL;
4985
4986         context->nx = true;
4987         context->ept_ad = accessed_dirty;
4988         context->page_fault = ept_page_fault;
4989         context->gva_to_gpa = ept_gva_to_gpa;
4990         context->sync_page = ept_sync_page;
4991         context->invlpg = ept_invlpg;
4992         context->update_pte = ept_update_pte;
4993         context->root_level = PT64_ROOT_4LEVEL;
4994         context->direct_map = false;
4995         context->mmu_role.as_u64 = new_role.as_u64;
4996
4997         update_permission_bitmask(vcpu, context, true);
4998         update_pkru_bitmask(vcpu, context, true);
4999         update_last_nonleaf_level(vcpu, context);
5000         reset_rsvds_bits_mask_ept(vcpu, context, execonly);
5001         reset_ept_shadow_zero_bits_mask(vcpu, context, execonly);
5002 }
5003 EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
5004
5005 static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
5006 {
5007         struct kvm_mmu *context = vcpu->arch.mmu;
5008
5009         kvm_init_shadow_mmu(vcpu);
5010         context->set_cr3           = kvm_x86_ops->set_cr3;
5011         context->get_cr3           = get_cr3;
5012         context->get_pdptr         = kvm_pdptr_read;
5013         context->inject_page_fault = kvm_inject_page_fault;
5014 }
5015
5016 static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
5017 {
5018         union kvm_mmu_role new_role = kvm_calc_mmu_role_common(vcpu, false);
5019         struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
5020
5021         new_role.base.word &= mmu_base_role_mask.word;
5022         if (new_role.as_u64 == g_context->mmu_role.as_u64)
5023                 return;
5024
5025         g_context->mmu_role.as_u64 = new_role.as_u64;
5026         g_context->get_cr3           = get_cr3;
5027         g_context->get_pdptr         = kvm_pdptr_read;
5028         g_context->inject_page_fault = kvm_inject_page_fault;
5029
5030         /*
5031          * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
5032          * L1's nested page tables (e.g. EPT12). The nested translation
5033          * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5034          * L2's page tables as the first level of translation and L1's
5035          * nested page tables as the second level of translation. Basically
5036          * the gva_to_gpa functions between mmu and nested_mmu are swapped.
5037          */
5038         if (!is_paging(vcpu)) {
5039                 g_context->nx = false;
5040                 g_context->root_level = 0;
5041                 g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
5042         } else if (is_long_mode(vcpu)) {
5043                 g_context->nx = is_nx(vcpu);
5044                 g_context->root_level = is_la57_mode(vcpu) ?
5045                                         PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
5046                 reset_rsvds_bits_mask(vcpu, g_context);
5047                 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5048         } else if (is_pae(vcpu)) {
5049                 g_context->nx = is_nx(vcpu);
5050                 g_context->root_level = PT32E_ROOT_LEVEL;
5051                 reset_rsvds_bits_mask(vcpu, g_context);
5052                 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5053         } else {
5054                 g_context->nx = false;
5055                 g_context->root_level = PT32_ROOT_LEVEL;
5056                 reset_rsvds_bits_mask(vcpu, g_context);
5057                 g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
5058         }
5059
5060         update_permission_bitmask(vcpu, g_context, false);
5061         update_pkru_bitmask(vcpu, g_context, false);
5062         update_last_nonleaf_level(vcpu, g_context);
5063 }
5064
5065 void kvm_init_mmu(struct kvm_vcpu *vcpu, bool reset_roots)
5066 {
5067         if (reset_roots) {
5068                 uint i;
5069
5070                 vcpu->arch.mmu->root_hpa = INVALID_PAGE;
5071
5072                 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5073                         vcpu->arch.mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5074         }
5075
5076         if (mmu_is_nested(vcpu))
5077                 init_kvm_nested_mmu(vcpu);
5078         else if (tdp_enabled)
5079                 init_kvm_tdp_mmu(vcpu);
5080         else
5081                 init_kvm_softmmu(vcpu);
5082 }
5083 EXPORT_SYMBOL_GPL(kvm_init_mmu);
5084
5085 static union kvm_mmu_page_role
5086 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu)
5087 {
5088         union kvm_mmu_role role;
5089
5090         if (tdp_enabled)
5091                 role = kvm_calc_tdp_mmu_root_page_role(vcpu, true);
5092         else
5093                 role = kvm_calc_shadow_mmu_root_page_role(vcpu, true);
5094
5095         return role.base;
5096 }
5097
5098 void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5099 {
5100         kvm_mmu_unload(vcpu);
5101         kvm_init_mmu(vcpu, true);
5102 }
5103 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5104
5105 int kvm_mmu_load(struct kvm_vcpu *vcpu)
5106 {
5107         int r;
5108
5109         r = mmu_topup_memory_caches(vcpu);
5110         if (r)
5111                 goto out;
5112         r = mmu_alloc_roots(vcpu);
5113         kvm_mmu_sync_roots(vcpu);
5114         if (r)
5115                 goto out;
5116         kvm_mmu_load_cr3(vcpu);
5117         kvm_x86_ops->tlb_flush(vcpu, true);
5118 out:
5119         return r;
5120 }
5121 EXPORT_SYMBOL_GPL(kvm_mmu_load);
5122
5123 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5124 {
5125         kvm_mmu_free_roots(vcpu, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
5126         WARN_ON(VALID_PAGE(vcpu->arch.root_mmu.root_hpa));
5127         kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
5128         WARN_ON(VALID_PAGE(vcpu->arch.guest_mmu.root_hpa));
5129 }
5130 EXPORT_SYMBOL_GPL(kvm_mmu_unload);
5131
5132 static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
5133                                   struct kvm_mmu_page *sp, u64 *spte,
5134                                   const void *new)
5135 {
5136         if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
5137                 ++vcpu->kvm->stat.mmu_pde_zapped;
5138                 return;
5139         }
5140
5141         ++vcpu->kvm->stat.mmu_pte_updated;
5142         vcpu->arch.mmu->update_pte(vcpu, sp, spte, new);
5143 }
5144
5145 static bool need_remote_flush(u64 old, u64 new)
5146 {
5147         if (!is_shadow_present_pte(old))
5148                 return false;
5149         if (!is_shadow_present_pte(new))
5150                 return true;
5151         if ((old ^ new) & PT64_BASE_ADDR_MASK)
5152                 return true;
5153         old ^= shadow_nx_mask;
5154         new ^= shadow_nx_mask;
5155         return (old & ~new & PT64_PERM_MASK) != 0;
5156 }
5157
5158 static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5159                                     int *bytes)
5160 {
5161         u64 gentry = 0;
5162         int r;
5163
5164         /*
5165          * Assume that the pte write on a page table of the same type
5166          * as the current vcpu paging mode since we update the sptes only
5167          * when they have the same mode.
5168          */
5169         if (is_pae(vcpu) && *bytes == 4) {
5170                 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5171                 *gpa &= ~(gpa_t)7;
5172                 *bytes = 8;
5173         }
5174
5175         if (*bytes == 4 || *bytes == 8) {
5176                 r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5177                 if (r)
5178                         gentry = 0;
5179         }
5180
5181         return gentry;
5182 }
5183
5184 /*
5185  * If we're seeing too many writes to a page, it may no longer be a page table,
5186  * or we may be forking, in which case it is better to unmap the page.
5187  */
5188 static bool detect_write_flooding(struct kvm_mmu_page *sp)
5189 {
5190         /*
5191          * Skip write-flooding detected for the sp whose level is 1, because
5192          * it can become unsync, then the guest page is not write-protected.
5193          */
5194         if (sp->role.level == PT_PAGE_TABLE_LEVEL)
5195                 return false;
5196
5197         atomic_inc(&sp->write_flooding_count);
5198         return atomic_read(&sp->write_flooding_count) >= 3;
5199 }
5200
5201 /*
5202  * Misaligned accesses are too much trouble to fix up; also, they usually
5203  * indicate a page is not used as a page table.
5204  */
5205 static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5206                                     int bytes)
5207 {
5208         unsigned offset, pte_size, misaligned;
5209
5210         pgprintk("misaligned: gpa %llx bytes %d role %x\n",
5211                  gpa, bytes, sp->role.word);
5212
5213         offset = offset_in_page(gpa);
5214         pte_size = sp->role.gpte_is_8_bytes ? 8 : 4;
5215
5216         /*
5217          * Sometimes, the OS only writes the last one bytes to update status
5218          * bits, for example, in linux, andb instruction is used in clear_bit().
5219          */
5220         if (!(offset & (pte_size - 1)) && bytes == 1)
5221                 return false;
5222
5223         misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5224         misaligned |= bytes < 4;
5225
5226         return misaligned;
5227 }
5228
5229 static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5230 {
5231         unsigned page_offset, quadrant;
5232         u64 *spte;
5233         int level;
5234
5235         page_offset = offset_in_page(gpa);
5236         level = sp->role.level;
5237         *nspte = 1;
5238         if (!sp->role.gpte_is_8_bytes) {
5239                 page_offset <<= 1;      /* 32->64 */
5240                 /*
5241                  * A 32-bit pde maps 4MB while the shadow pdes map
5242                  * only 2MB.  So we need to double the offset again
5243                  * and zap two pdes instead of one.
5244                  */
5245                 if (level == PT32_ROOT_LEVEL) {
5246                         page_offset &= ~7; /* kill rounding error */
5247                         page_offset <<= 1;
5248                         *nspte = 2;
5249                 }
5250                 quadrant = page_offset >> PAGE_SHIFT;
5251                 page_offset &= ~PAGE_MASK;
5252                 if (quadrant != sp->role.quadrant)
5253                         return NULL;
5254         }
5255
5256         spte = &sp->spt[page_offset / sizeof(*spte)];
5257         return spte;
5258 }
5259
5260 static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
5261                               const u8 *new, int bytes,
5262                               struct kvm_page_track_notifier_node *node)
5263 {
5264         gfn_t gfn = gpa >> PAGE_SHIFT;
5265         struct kvm_mmu_page *sp;
5266         LIST_HEAD(invalid_list);
5267         u64 entry, gentry, *spte;
5268         int npte;
5269         bool remote_flush, local_flush;
5270
5271         /*
5272          * If we don't have indirect shadow pages, it means no page is
5273          * write-protected, so we can exit simply.
5274          */
5275         if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
5276                 return;
5277
5278         remote_flush = local_flush = false;
5279
5280         pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
5281
5282         /*
5283          * No need to care whether allocation memory is successful
5284          * or not since pte prefetch is skiped if it does not have
5285          * enough objects in the cache.
5286          */
5287         mmu_topup_memory_caches(vcpu);
5288
5289         spin_lock(&vcpu->kvm->mmu_lock);
5290
5291         gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5292
5293         ++vcpu->kvm->stat.mmu_pte_write;
5294         kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
5295
5296         for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
5297                 if (detect_write_misaligned(sp, gpa, bytes) ||
5298                       detect_write_flooding(sp)) {
5299                         kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5300                         ++vcpu->kvm->stat.mmu_flooded;
5301                         continue;
5302                 }
5303
5304                 spte = get_written_sptes(sp, gpa, &npte);
5305                 if (!spte)
5306                         continue;
5307
5308                 local_flush = true;
5309                 while (npte--) {
5310                         u32 base_role = vcpu->arch.mmu->mmu_role.base.word;
5311
5312                         entry = *spte;
5313                         mmu_page_zap_pte(vcpu->kvm, sp, spte);
5314                         if (gentry &&
5315                               !((sp->role.word ^ base_role)
5316                               & mmu_base_role_mask.word) && rmap_can_add(vcpu))
5317                                 mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
5318                         if (need_remote_flush(entry, *spte))
5319                                 remote_flush = true;
5320                         ++spte;
5321                 }
5322         }
5323         kvm_mmu_flush_or_zap(vcpu, &invalid_list, remote_flush, local_flush);
5324         kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
5325         spin_unlock(&vcpu->kvm->mmu_lock);
5326 }
5327
5328 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
5329 {
5330         gpa_t gpa;
5331         int r;
5332
5333         if (vcpu->arch.mmu->direct_map)
5334                 return 0;
5335
5336         gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
5337
5338         r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
5339
5340         return r;
5341 }
5342 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
5343
5344 static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
5345 {
5346         LIST_HEAD(invalid_list);
5347
5348         if (likely(kvm_mmu_available_pages(vcpu->kvm) >= KVM_MIN_FREE_MMU_PAGES))
5349                 return 0;
5350
5351         while (kvm_mmu_available_pages(vcpu->kvm) < KVM_REFILL_PAGES) {
5352                 if (!prepare_zap_oldest_mmu_page(vcpu->kvm, &invalid_list))
5353                         break;
5354
5355                 ++vcpu->kvm->stat.mmu_recycled;
5356         }
5357         kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
5358
5359         if (!kvm_mmu_available_pages(vcpu->kvm))
5360                 return -ENOSPC;
5361         return 0;
5362 }
5363
5364 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u64 error_code,
5365                        void *insn, int insn_len)
5366 {
5367         int r, emulation_type = 0;
5368         enum emulation_result er;
5369         bool direct = vcpu->arch.mmu->direct_map;
5370
5371         /* With shadow page tables, fault_address contains a GVA or nGPA.  */
5372         if (vcpu->arch.mmu->direct_map) {
5373                 vcpu->arch.gpa_available = true;
5374                 vcpu->arch.gpa_val = cr2;
5375         }
5376
5377         r = RET_PF_INVALID;
5378         if (unlikely(error_code & PFERR_RSVD_MASK)) {
5379                 r = handle_mmio_page_fault(vcpu, cr2, direct);
5380                 if (r == RET_PF_EMULATE)
5381                         goto emulate;
5382         }
5383
5384         if (r == RET_PF_INVALID) {
5385                 r = vcpu->arch.mmu->page_fault(vcpu, cr2,
5386                                                lower_32_bits(error_code),
5387                                                false);
5388                 WARN_ON(r == RET_PF_INVALID);
5389         }
5390
5391         if (r == RET_PF_RETRY)
5392                 return 1;
5393         if (r < 0)
5394                 return r;
5395
5396         /*
5397          * Before emulating the instruction, check if the error code
5398          * was due to a RO violation while translating the guest page.
5399          * This can occur when using nested virtualization with nested
5400          * paging in both guests. If true, we simply unprotect the page
5401          * and resume the guest.
5402          */
5403         if (vcpu->arch.mmu->direct_map &&
5404             (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5405                 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2));
5406                 return 1;
5407         }
5408
5409         /*
5410          * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5411          * optimistically try to just unprotect the page and let the processor
5412          * re-execute the instruction that caused the page fault.  Do not allow
5413          * retrying MMIO emulation, as it's not only pointless but could also
5414          * cause us to enter an infinite loop because the processor will keep
5415          * faulting on the non-existent MMIO address.  Retrying an instruction
5416          * from a nested guest is also pointless and dangerous as we are only
5417          * explicitly shadowing L1's page tables, i.e. unprotecting something
5418          * for L1 isn't going to magically fix whatever issue cause L2 to fail.
5419          */
5420         if (!mmio_info_in_cache(vcpu, cr2, direct) && !is_guest_mode(vcpu))
5421                 emulation_type = EMULTYPE_ALLOW_RETRY;
5422 emulate:
5423         /*
5424          * On AMD platforms, under certain conditions insn_len may be zero on #NPF.
5425          * This can happen if a guest gets a page-fault on data access but the HW
5426          * table walker is not able to read the instruction page (e.g instruction
5427          * page is not present in memory). In those cases we simply restart the
5428          * guest, with the exception of AMD Erratum 1096 which is unrecoverable.
5429          */
5430         if (unlikely(insn && !insn_len)) {
5431                 if (!kvm_x86_ops->need_emulation_on_page_fault(vcpu))
5432                         return 1;
5433         }
5434
5435         er = x86_emulate_instruction(vcpu, cr2, emulation_type, insn, insn_len);
5436
5437         switch (er) {
5438         case EMULATE_DONE:
5439                 return 1;
5440         case EMULATE_USER_EXIT:
5441                 ++vcpu->stat.mmio_exits;
5442                 /* fall through */
5443         case EMULATE_FAIL:
5444                 return 0;
5445         default:
5446                 BUG();
5447         }
5448 }
5449 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5450
5451 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
5452 {
5453         struct kvm_mmu *mmu = vcpu->arch.mmu;
5454         int i;
5455
5456         /* INVLPG on a * non-canonical address is a NOP according to the SDM.  */
5457         if (is_noncanonical_address(gva, vcpu))
5458                 return;
5459
5460         mmu->invlpg(vcpu, gva, mmu->root_hpa);
5461
5462         /*
5463          * INVLPG is required to invalidate any global mappings for the VA,
5464          * irrespective of PCID. Since it would take us roughly similar amount
5465          * of work to determine whether any of the prev_root mappings of the VA
5466          * is marked global, or to just sync it blindly, so we might as well
5467          * just always sync it.
5468          *
5469          * Mappings not reachable via the current cr3 or the prev_roots will be
5470          * synced when switching to that cr3, so nothing needs to be done here
5471          * for them.
5472          */
5473         for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5474                 if (VALID_PAGE(mmu->prev_roots[i].hpa))
5475                         mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5476
5477         kvm_x86_ops->tlb_flush_gva(vcpu, gva);
5478         ++vcpu->stat.invlpg;
5479 }
5480 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5481
5482 void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5483 {
5484         struct kvm_mmu *mmu = vcpu->arch.mmu;
5485         bool tlb_flush = false;
5486         uint i;
5487
5488         if (pcid == kvm_get_active_pcid(vcpu)) {
5489                 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5490                 tlb_flush = true;
5491         }
5492
5493         for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5494                 if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
5495                     pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].cr3)) {
5496                         mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5497                         tlb_flush = true;
5498                 }
5499         }
5500
5501         if (tlb_flush)
5502                 kvm_x86_ops->tlb_flush_gva(vcpu, gva);
5503
5504         ++vcpu->stat.invlpg;
5505
5506         /*
5507          * Mappings not reachable via the current cr3 or the prev_roots will be
5508          * synced when switching to that cr3, so nothing needs to be done here
5509          * for them.
5510          */
5511 }
5512 EXPORT_SYMBOL_GPL(kvm_mmu_invpcid_gva);
5513
5514 void kvm_enable_tdp(void)
5515 {
5516         tdp_enabled = true;
5517 }
5518 EXPORT_SYMBOL_GPL(kvm_enable_tdp);
5519
5520 void kvm_disable_tdp(void)
5521 {
5522         tdp_enabled = false;
5523 }
5524 EXPORT_SYMBOL_GPL(kvm_disable_tdp);
5525
5526
5527 /* The return value indicates if tlb flush on all vcpus is needed. */
5528 typedef bool (*slot_level_handler) (struct kvm *kvm, struct kvm_rmap_head *rmap_head);
5529
5530 /* The caller should hold mmu-lock before calling this function. */
5531 static __always_inline bool
5532 slot_handle_level_range(struct kvm *kvm, struct kvm_memory_slot *memslot,
5533                         slot_level_handler fn, int start_level, int end_level,
5534                         gfn_t start_gfn, gfn_t end_gfn, bool lock_flush_tlb)
5535 {
5536         struct slot_rmap_walk_iterator iterator;
5537         bool flush = false;
5538
5539         for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
5540                         end_gfn, &iterator) {
5541                 if (iterator.rmap)
5542                         flush |= fn(kvm, iterator.rmap);
5543
5544                 if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
5545                         if (flush && lock_flush_tlb) {
5546                                 kvm_flush_remote_tlbs_with_address(kvm,
5547                                                 start_gfn,
5548                                                 iterator.gfn - start_gfn + 1);
5549                                 flush = false;
5550                         }
5551                         cond_resched_lock(&kvm->mmu_lock);
5552                 }
5553         }
5554
5555         if (flush && lock_flush_tlb) {
5556                 kvm_flush_remote_tlbs_with_address(kvm, start_gfn,
5557                                                    end_gfn - start_gfn + 1);
5558                 flush = false;
5559         }
5560
5561         return flush;
5562 }
5563
5564 static __always_inline bool
5565 slot_handle_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5566                   slot_level_handler fn, int start_level, int end_level,
5567                   bool lock_flush_tlb)
5568 {
5569         return slot_handle_level_range(kvm, memslot, fn, start_level,
5570                         end_level, memslot->base_gfn,
5571                         memslot->base_gfn + memslot->npages - 1,
5572                         lock_flush_tlb);
5573 }
5574
5575 static __always_inline bool
5576 slot_handle_all_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5577                       slot_level_handler fn, bool lock_flush_tlb)
5578 {
5579         return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5580                                  PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5581 }
5582
5583 static __always_inline bool
5584 slot_handle_large_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5585                         slot_level_handler fn, bool lock_flush_tlb)
5586 {
5587         return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL + 1,
5588                                  PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5589 }
5590
5591 static __always_inline bool
5592 slot_handle_leaf(struct kvm *kvm, struct kvm_memory_slot *memslot,
5593                  slot_level_handler fn, bool lock_flush_tlb)
5594 {
5595         return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5596                                  PT_PAGE_TABLE_LEVEL, lock_flush_tlb);
5597 }
5598
5599 static void free_mmu_pages(struct kvm_vcpu *vcpu)
5600 {
5601         free_page((unsigned long)vcpu->arch.mmu->pae_root);
5602         free_page((unsigned long)vcpu->arch.mmu->lm_root);
5603 }
5604
5605 static int alloc_mmu_pages(struct kvm_vcpu *vcpu)
5606 {
5607         struct page *page;
5608         int i;
5609
5610         if (tdp_enabled)
5611                 return 0;
5612
5613         /*
5614          * When emulating 32-bit mode, cr3 is only 32 bits even on x86_64.
5615          * Therefore we need to allocate shadow page tables in the first
5616          * 4GB of memory, which happens to fit the DMA32 zone.
5617          */
5618         page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
5619         if (!page)
5620                 return -ENOMEM;
5621
5622         vcpu->arch.mmu->pae_root = page_address(page);
5623         for (i = 0; i < 4; ++i)
5624                 vcpu->arch.mmu->pae_root[i] = INVALID_PAGE;
5625
5626         return 0;
5627 }
5628
5629 int kvm_mmu_create(struct kvm_vcpu *vcpu)
5630 {
5631         uint i;
5632
5633         vcpu->arch.mmu = &vcpu->arch.root_mmu;
5634         vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
5635
5636         vcpu->arch.root_mmu.root_hpa = INVALID_PAGE;
5637         vcpu->arch.root_mmu.root_cr3 = 0;
5638         vcpu->arch.root_mmu.translate_gpa = translate_gpa;
5639         for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5640                 vcpu->arch.root_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5641
5642         vcpu->arch.guest_mmu.root_hpa = INVALID_PAGE;
5643         vcpu->arch.guest_mmu.root_cr3 = 0;
5644         vcpu->arch.guest_mmu.translate_gpa = translate_gpa;
5645         for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5646                 vcpu->arch.guest_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5647
5648         vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
5649         return alloc_mmu_pages(vcpu);
5650 }
5651
5652 static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
5653                         struct kvm_memory_slot *slot,
5654                         struct kvm_page_track_notifier_node *node)
5655 {
5656         struct kvm_mmu_page *sp;
5657         LIST_HEAD(invalid_list);
5658         unsigned long i;
5659         bool flush;
5660         gfn_t gfn;
5661
5662         spin_lock(&kvm->mmu_lock);
5663
5664         if (list_empty(&kvm->arch.active_mmu_pages))
5665                 goto out_unlock;
5666
5667         flush = slot_handle_all_level(kvm, slot, kvm_zap_rmapp, false);
5668
5669         for (i = 0; i < slot->npages; i++) {
5670                 gfn = slot->base_gfn + i;
5671
5672                 for_each_valid_sp(kvm, sp, gfn) {
5673                         if (sp->gfn != gfn)
5674                                 continue;
5675
5676                         kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
5677                 }
5678                 if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
5679                         kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
5680                         flush = false;
5681                         cond_resched_lock(&kvm->mmu_lock);
5682                 }
5683         }
5684         kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
5685
5686 out_unlock:
5687         spin_unlock(&kvm->mmu_lock);
5688 }
5689
5690 void kvm_mmu_init_vm(struct kvm *kvm)
5691 {
5692         struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5693
5694         node->track_write = kvm_mmu_pte_write;
5695         node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
5696         kvm_page_track_register_notifier(kvm, node);
5697 }
5698
5699 void kvm_mmu_uninit_vm(struct kvm *kvm)
5700 {
5701         struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5702
5703         kvm_page_track_unregister_notifier(kvm, node);
5704 }
5705
5706 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
5707 {
5708         struct kvm_memslots *slots;
5709         struct kvm_memory_slot *memslot;
5710         int i;
5711
5712         spin_lock(&kvm->mmu_lock);
5713         for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5714                 slots = __kvm_memslots(kvm, i);
5715                 kvm_for_each_memslot(memslot, slots) {
5716                         gfn_t start, end;
5717
5718                         start = max(gfn_start, memslot->base_gfn);
5719                         end = min(gfn_end, memslot->base_gfn + memslot->npages);
5720                         if (start >= end)
5721                                 continue;
5722
5723                         slot_handle_level_range(kvm, memslot, kvm_zap_rmapp,
5724                                                 PT_PAGE_TABLE_LEVEL, PT_MAX_HUGEPAGE_LEVEL,
5725                                                 start, end - 1, true);
5726                 }
5727         }
5728
5729         spin_unlock(&kvm->mmu_lock);
5730 }
5731
5732 static bool slot_rmap_write_protect(struct kvm *kvm,
5733                                     struct kvm_rmap_head *rmap_head)
5734 {
5735         return __rmap_write_protect(kvm, rmap_head, false);
5736 }
5737
5738 void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
5739                                       struct kvm_memory_slot *memslot)
5740 {
5741         bool flush;
5742
5743         spin_lock(&kvm->mmu_lock);
5744         flush = slot_handle_all_level(kvm, memslot, slot_rmap_write_protect,
5745                                       false);
5746         spin_unlock(&kvm->mmu_lock);
5747
5748         /*
5749          * kvm_mmu_slot_remove_write_access() and kvm_vm_ioctl_get_dirty_log()
5750          * which do tlb flush out of mmu-lock should be serialized by
5751          * kvm->slots_lock otherwise tlb flush would be missed.
5752          */
5753         lockdep_assert_held(&kvm->slots_lock);
5754
5755         /*
5756          * We can flush all the TLBs out of the mmu lock without TLB
5757          * corruption since we just change the spte from writable to
5758          * readonly so that we only need to care the case of changing
5759          * spte from present to present (changing the spte from present
5760          * to nonpresent will flush all the TLBs immediately), in other
5761          * words, the only case we care is mmu_spte_update() where we
5762          * have checked SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE
5763          * instead of PT_WRITABLE_MASK, that means it does not depend
5764          * on PT_WRITABLE_MASK anymore.
5765          */
5766         if (flush)
5767                 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5768                         memslot->npages);
5769 }
5770
5771 static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
5772                                          struct kvm_rmap_head *rmap_head)
5773 {
5774         u64 *sptep;
5775         struct rmap_iterator iter;
5776         int need_tlb_flush = 0;
5777         kvm_pfn_t pfn;
5778         struct kvm_mmu_page *sp;
5779
5780 restart:
5781         for_each_rmap_spte(rmap_head, &iter, sptep) {
5782                 sp = page_header(__pa(sptep));
5783                 pfn = spte_to_pfn(*sptep);
5784
5785                 /*
5786                  * We cannot do huge page mapping for indirect shadow pages,
5787                  * which are found on the last rmap (level = 1) when not using
5788                  * tdp; such shadow pages are synced with the page table in
5789                  * the guest, and the guest page table is using 4K page size
5790                  * mapping if the indirect sp has level = 1.
5791                  */
5792                 if (sp->role.direct &&
5793                         !kvm_is_reserved_pfn(pfn) &&
5794                         PageTransCompoundMap(pfn_to_page(pfn))) {
5795                         pte_list_remove(rmap_head, sptep);
5796
5797                         if (kvm_available_flush_tlb_with_range())
5798                                 kvm_flush_remote_tlbs_with_address(kvm, sp->gfn,
5799                                         KVM_PAGES_PER_HPAGE(sp->role.level));
5800                         else
5801                                 need_tlb_flush = 1;
5802
5803                         goto restart;
5804                 }
5805         }
5806
5807         return need_tlb_flush;
5808 }
5809
5810 void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
5811                                    const struct kvm_memory_slot *memslot)
5812 {
5813         /* FIXME: const-ify all uses of struct kvm_memory_slot.  */
5814         spin_lock(&kvm->mmu_lock);
5815         slot_handle_leaf(kvm, (struct kvm_memory_slot *)memslot,
5816                          kvm_mmu_zap_collapsible_spte, true);
5817         spin_unlock(&kvm->mmu_lock);
5818 }
5819
5820 void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
5821                                    struct kvm_memory_slot *memslot)
5822 {
5823         bool flush;
5824
5825         spin_lock(&kvm->mmu_lock);
5826         flush = slot_handle_leaf(kvm, memslot, __rmap_clear_dirty, false);
5827         spin_unlock(&kvm->mmu_lock);
5828
5829         lockdep_assert_held(&kvm->slots_lock);
5830
5831         /*
5832          * It's also safe to flush TLBs out of mmu lock here as currently this
5833          * function is only used for dirty logging, in which case flushing TLB
5834          * out of mmu lock also guarantees no dirty pages will be lost in
5835          * dirty_bitmap.
5836          */
5837         if (flush)
5838                 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5839                                 memslot->npages);
5840 }
5841 EXPORT_SYMBOL_GPL(kvm_mmu_slot_leaf_clear_dirty);
5842
5843 void kvm_mmu_slot_largepage_remove_write_access(struct kvm *kvm,
5844                                         struct kvm_memory_slot *memslot)
5845 {
5846         bool flush;
5847
5848         spin_lock(&kvm->mmu_lock);
5849         flush = slot_handle_large_level(kvm, memslot, slot_rmap_write_protect,
5850                                         false);
5851         spin_unlock(&kvm->mmu_lock);
5852
5853         /* see kvm_mmu_slot_remove_write_access */
5854         lockdep_assert_held(&kvm->slots_lock);
5855
5856         if (flush)
5857                 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5858                                 memslot->npages);
5859 }
5860 EXPORT_SYMBOL_GPL(kvm_mmu_slot_largepage_remove_write_access);
5861
5862 void kvm_mmu_slot_set_dirty(struct kvm *kvm,
5863                             struct kvm_memory_slot *memslot)
5864 {
5865         bool flush;
5866
5867         spin_lock(&kvm->mmu_lock);
5868         flush = slot_handle_all_level(kvm, memslot, __rmap_set_dirty, false);
5869         spin_unlock(&kvm->mmu_lock);
5870
5871         lockdep_assert_held(&kvm->slots_lock);
5872
5873         /* see kvm_mmu_slot_leaf_clear_dirty */
5874         if (flush)
5875                 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5876                                 memslot->npages);
5877 }
5878 EXPORT_SYMBOL_GPL(kvm_mmu_slot_set_dirty);
5879
5880 static void __kvm_mmu_zap_all(struct kvm *kvm, bool mmio_only)
5881 {
5882         struct kvm_mmu_page *sp, *node;
5883         LIST_HEAD(invalid_list);
5884         int ign;
5885
5886         spin_lock(&kvm->mmu_lock);
5887 restart:
5888         list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
5889                 if (mmio_only && !sp->mmio_cached)
5890                         continue;
5891                 if (sp->role.invalid && sp->root_count)
5892                         continue;
5893                 if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign)) {
5894                         WARN_ON_ONCE(mmio_only);
5895                         goto restart;
5896                 }
5897                 if (cond_resched_lock(&kvm->mmu_lock))
5898                         goto restart;
5899         }
5900
5901         kvm_mmu_commit_zap_page(kvm, &invalid_list);
5902         spin_unlock(&kvm->mmu_lock);
5903 }
5904
5905 void kvm_mmu_zap_all(struct kvm *kvm)
5906 {
5907         return __kvm_mmu_zap_all(kvm, false);
5908 }
5909
5910 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
5911 {
5912         WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
5913
5914         gen &= MMIO_SPTE_GEN_MASK;
5915
5916         /*
5917          * Generation numbers are incremented in multiples of the number of
5918          * address spaces in order to provide unique generations across all
5919          * address spaces.  Strip what is effectively the address space
5920          * modifier prior to checking for a wrap of the MMIO generation so
5921          * that a wrap in any address space is detected.
5922          */
5923         gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
5924
5925         /*
5926          * The very rare case: if the MMIO generation number has wrapped,
5927          * zap all shadow pages.
5928          */
5929         if (unlikely(gen == 0)) {
5930                 kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
5931                 __kvm_mmu_zap_all(kvm, true);
5932         }
5933 }
5934
5935 static unsigned long
5936 mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
5937 {
5938         struct kvm *kvm;
5939         int nr_to_scan = sc->nr_to_scan;
5940         unsigned long freed = 0;
5941
5942         mutex_lock(&kvm_lock);
5943
5944         list_for_each_entry(kvm, &vm_list, vm_list) {
5945                 int idx;
5946                 LIST_HEAD(invalid_list);
5947
5948                 /*
5949                  * Never scan more than sc->nr_to_scan VM instances.
5950                  * Will not hit this condition practically since we do not try
5951                  * to shrink more than one VM and it is very unlikely to see
5952                  * !n_used_mmu_pages so many times.
5953                  */
5954                 if (!nr_to_scan--)
5955                         break;
5956                 /*
5957                  * n_used_mmu_pages is accessed without holding kvm->mmu_lock
5958                  * here. We may skip a VM instance errorneosly, but we do not
5959                  * want to shrink a VM that only started to populate its MMU
5960                  * anyway.
5961                  */
5962                 if (!kvm->arch.n_used_mmu_pages)
5963                         continue;
5964
5965                 idx = srcu_read_lock(&kvm->srcu);
5966                 spin_lock(&kvm->mmu_lock);
5967
5968                 if (prepare_zap_oldest_mmu_page(kvm, &invalid_list))
5969                         freed++;
5970                 kvm_mmu_commit_zap_page(kvm, &invalid_list);
5971
5972                 spin_unlock(&kvm->mmu_lock);
5973                 srcu_read_unlock(&kvm->srcu, idx);
5974
5975                 /*
5976                  * unfair on small ones
5977                  * per-vm shrinkers cry out
5978                  * sadness comes quickly
5979                  */
5980                 list_move_tail(&kvm->vm_list, &vm_list);
5981                 break;
5982         }
5983
5984         mutex_unlock(&kvm_lock);
5985         return freed;
5986 }
5987
5988 static unsigned long
5989 mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
5990 {
5991         return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
5992 }
5993
5994 static struct shrinker mmu_shrinker = {
5995         .count_objects = mmu_shrink_count,
5996         .scan_objects = mmu_shrink_scan,
5997         .seeks = DEFAULT_SEEKS * 10,
5998 };
5999
6000 static void mmu_destroy_caches(void)
6001 {
6002         kmem_cache_destroy(pte_list_desc_cache);
6003         kmem_cache_destroy(mmu_page_header_cache);
6004 }
6005
6006 static void kvm_set_mmio_spte_mask(void)
6007 {
6008         u64 mask;
6009
6010         /*
6011          * Set the reserved bits and the present bit of an paging-structure
6012          * entry to generate page fault with PFER.RSV = 1.
6013          */
6014
6015         /*
6016          * Mask the uppermost physical address bit, which would be reserved as
6017          * long as the supported physical address width is less than 52.
6018          */
6019         mask = 1ull << 51;
6020
6021         /* Set the present bit. */
6022         mask |= 1ull;
6023
6024         /*
6025          * If reserved bit is not supported, clear the present bit to disable
6026          * mmio page fault.
6027          */
6028         if (IS_ENABLED(CONFIG_X86_64) && shadow_phys_bits == 52)
6029                 mask &= ~1ull;
6030
6031         kvm_mmu_set_mmio_spte_mask(mask, mask);
6032 }
6033
6034 int kvm_mmu_module_init(void)
6035 {
6036         int ret = -ENOMEM;
6037
6038         /*
6039          * MMU roles use union aliasing which is, generally speaking, an
6040          * undefined behavior. However, we supposedly know how compilers behave
6041          * and the current status quo is unlikely to change. Guardians below are
6042          * supposed to let us know if the assumption becomes false.
6043          */
6044         BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
6045         BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
6046         BUILD_BUG_ON(sizeof(union kvm_mmu_role) != sizeof(u64));
6047
6048         kvm_mmu_reset_all_pte_masks();
6049
6050         kvm_set_mmio_spte_mask();
6051
6052         pte_list_desc_cache = kmem_cache_create("pte_list_desc",
6053                                             sizeof(struct pte_list_desc),
6054                                             0, SLAB_ACCOUNT, NULL);
6055         if (!pte_list_desc_cache)
6056                 goto out;
6057
6058         mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
6059                                                   sizeof(struct kvm_mmu_page),
6060                                                   0, SLAB_ACCOUNT, NULL);
6061         if (!mmu_page_header_cache)
6062                 goto out;
6063
6064         if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
6065                 goto out;
6066
6067         ret = register_shrinker(&mmu_shrinker);
6068         if (ret)
6069                 goto out;
6070
6071         return 0;
6072
6073 out:
6074         mmu_destroy_caches();
6075         return ret;
6076 }
6077
6078 /*
6079  * Calculate mmu pages needed for kvm.
6080  */
6081 unsigned long kvm_mmu_calculate_default_mmu_pages(struct kvm *kvm)
6082 {
6083         unsigned long nr_mmu_pages;
6084         unsigned long nr_pages = 0;
6085         struct kvm_memslots *slots;
6086         struct kvm_memory_slot *memslot;
6087         int i;
6088
6089         for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
6090                 slots = __kvm_memslots(kvm, i);
6091
6092                 kvm_for_each_memslot(memslot, slots)
6093                         nr_pages += memslot->npages;
6094         }
6095
6096         nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
6097         nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
6098
6099         return nr_mmu_pages;
6100 }
6101
6102 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
6103 {
6104         kvm_mmu_unload(vcpu);
6105         free_mmu_pages(vcpu);
6106         mmu_free_memory_caches(vcpu);
6107 }
6108
6109 void kvm_mmu_module_exit(void)
6110 {
6111         mmu_destroy_caches();
6112         percpu_counter_destroy(&kvm_total_used_mmu_pages);
6113         unregister_shrinker(&mmu_shrinker);
6114         mmu_audit_disable();
6115 }