kvm: mmu: ITLB_MULTIHIT mitigation
[muen/linux.git] / arch / x86 / kvm / mmu.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Kernel-based Virtual Machine driver for Linux
4  *
5  * This module enables machines with Intel VT-x extensions to run virtual
6  * machines without emulation or binary translation.
7  *
8  * MMU support
9  *
10  * Copyright (C) 2006 Qumranet, Inc.
11  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
12  *
13  * Authors:
14  *   Yaniv Kamay  <yaniv@qumranet.com>
15  *   Avi Kivity   <avi@qumranet.com>
16  */
17
18 #include "irq.h"
19 #include "mmu.h"
20 #include "x86.h"
21 #include "kvm_cache_regs.h"
22 #include "cpuid.h"
23
24 #include <linux/kvm_host.h>
25 #include <linux/types.h>
26 #include <linux/string.h>
27 #include <linux/mm.h>
28 #include <linux/highmem.h>
29 #include <linux/moduleparam.h>
30 #include <linux/export.h>
31 #include <linux/swap.h>
32 #include <linux/hugetlb.h>
33 #include <linux/compiler.h>
34 #include <linux/srcu.h>
35 #include <linux/slab.h>
36 #include <linux/sched/signal.h>
37 #include <linux/uaccess.h>
38 #include <linux/hash.h>
39 #include <linux/kern_levels.h>
40
41 #include <asm/page.h>
42 #include <asm/pat.h>
43 #include <asm/cmpxchg.h>
44 #include <asm/e820/api.h>
45 #include <asm/io.h>
46 #include <asm/vmx.h>
47 #include <asm/kvm_page_track.h>
48 #include "trace.h"
49
50 extern bool itlb_multihit_kvm_mitigation;
51
52 static int __read_mostly nx_huge_pages = -1;
53
54 static int set_nx_huge_pages(const char *val, const struct kernel_param *kp);
55
56 static struct kernel_param_ops nx_huge_pages_ops = {
57         .set = set_nx_huge_pages,
58         .get = param_get_bool,
59 };
60
61 module_param_cb(nx_huge_pages, &nx_huge_pages_ops, &nx_huge_pages, 0644);
62 __MODULE_PARM_TYPE(nx_huge_pages, "bool");
63
64 /*
65  * When setting this variable to true it enables Two-Dimensional-Paging
66  * where the hardware walks 2 page tables:
67  * 1. the guest-virtual to guest-physical
68  * 2. while doing 1. it walks guest-physical to host-physical
69  * If the hardware supports that we don't need to do shadow paging.
70  */
71 bool tdp_enabled = false;
72
73 enum {
74         AUDIT_PRE_PAGE_FAULT,
75         AUDIT_POST_PAGE_FAULT,
76         AUDIT_PRE_PTE_WRITE,
77         AUDIT_POST_PTE_WRITE,
78         AUDIT_PRE_SYNC,
79         AUDIT_POST_SYNC
80 };
81
82 #undef MMU_DEBUG
83
84 #ifdef MMU_DEBUG
85 static bool dbg = 0;
86 module_param(dbg, bool, 0644);
87
88 #define pgprintk(x...) do { if (dbg) printk(x); } while (0)
89 #define rmap_printk(x...) do { if (dbg) printk(x); } while (0)
90 #define MMU_WARN_ON(x) WARN_ON(x)
91 #else
92 #define pgprintk(x...) do { } while (0)
93 #define rmap_printk(x...) do { } while (0)
94 #define MMU_WARN_ON(x) do { } while (0)
95 #endif
96
97 #define PTE_PREFETCH_NUM                8
98
99 #define PT_FIRST_AVAIL_BITS_SHIFT 10
100 #define PT64_SECOND_AVAIL_BITS_SHIFT 54
101
102 /*
103  * The mask used to denote special SPTEs, which can be either MMIO SPTEs or
104  * Access Tracking SPTEs.
105  */
106 #define SPTE_SPECIAL_MASK (3ULL << 52)
107 #define SPTE_AD_ENABLED_MASK (0ULL << 52)
108 #define SPTE_AD_DISABLED_MASK (1ULL << 52)
109 #define SPTE_AD_WRPROT_ONLY_MASK (2ULL << 52)
110 #define SPTE_MMIO_MASK (3ULL << 52)
111
112 #define PT64_LEVEL_BITS 9
113
114 #define PT64_LEVEL_SHIFT(level) \
115                 (PAGE_SHIFT + (level - 1) * PT64_LEVEL_BITS)
116
117 #define PT64_INDEX(address, level)\
118         (((address) >> PT64_LEVEL_SHIFT(level)) & ((1 << PT64_LEVEL_BITS) - 1))
119
120
121 #define PT32_LEVEL_BITS 10
122
123 #define PT32_LEVEL_SHIFT(level) \
124                 (PAGE_SHIFT + (level - 1) * PT32_LEVEL_BITS)
125
126 #define PT32_LVL_OFFSET_MASK(level) \
127         (PT32_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
128                                                 * PT32_LEVEL_BITS))) - 1))
129
130 #define PT32_INDEX(address, level)\
131         (((address) >> PT32_LEVEL_SHIFT(level)) & ((1 << PT32_LEVEL_BITS) - 1))
132
133
134 #ifdef CONFIG_DYNAMIC_PHYSICAL_MASK
135 #define PT64_BASE_ADDR_MASK (physical_mask & ~(u64)(PAGE_SIZE-1))
136 #else
137 #define PT64_BASE_ADDR_MASK (((1ULL << 52) - 1) & ~(u64)(PAGE_SIZE-1))
138 #endif
139 #define PT64_LVL_ADDR_MASK(level) \
140         (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
141                                                 * PT64_LEVEL_BITS))) - 1))
142 #define PT64_LVL_OFFSET_MASK(level) \
143         (PT64_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
144                                                 * PT64_LEVEL_BITS))) - 1))
145
146 #define PT32_BASE_ADDR_MASK PAGE_MASK
147 #define PT32_DIR_BASE_ADDR_MASK \
148         (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + PT32_LEVEL_BITS)) - 1))
149 #define PT32_LVL_ADDR_MASK(level) \
150         (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
151                                             * PT32_LEVEL_BITS))) - 1))
152
153 #define PT64_PERM_MASK (PT_PRESENT_MASK | PT_WRITABLE_MASK | shadow_user_mask \
154                         | shadow_x_mask | shadow_nx_mask | shadow_me_mask)
155
156 #define ACC_EXEC_MASK    1
157 #define ACC_WRITE_MASK   PT_WRITABLE_MASK
158 #define ACC_USER_MASK    PT_USER_MASK
159 #define ACC_ALL          (ACC_EXEC_MASK | ACC_WRITE_MASK | ACC_USER_MASK)
160
161 /* The mask for the R/X bits in EPT PTEs */
162 #define PT64_EPT_READABLE_MASK                  0x1ull
163 #define PT64_EPT_EXECUTABLE_MASK                0x4ull
164
165 #include <trace/events/kvm.h>
166
167 #define SPTE_HOST_WRITEABLE     (1ULL << PT_FIRST_AVAIL_BITS_SHIFT)
168 #define SPTE_MMU_WRITEABLE      (1ULL << (PT_FIRST_AVAIL_BITS_SHIFT + 1))
169
170 #define SHADOW_PT_INDEX(addr, level) PT64_INDEX(addr, level)
171
172 /* make pte_list_desc fit well in cache line */
173 #define PTE_LIST_EXT 3
174
175 /*
176  * Return values of handle_mmio_page_fault and mmu.page_fault:
177  * RET_PF_RETRY: let CPU fault again on the address.
178  * RET_PF_EMULATE: mmio page fault, emulate the instruction directly.
179  *
180  * For handle_mmio_page_fault only:
181  * RET_PF_INVALID: the spte is invalid, let the real page fault path update it.
182  */
183 enum {
184         RET_PF_RETRY = 0,
185         RET_PF_EMULATE = 1,
186         RET_PF_INVALID = 2,
187 };
188
189 struct pte_list_desc {
190         u64 *sptes[PTE_LIST_EXT];
191         struct pte_list_desc *more;
192 };
193
194 struct kvm_shadow_walk_iterator {
195         u64 addr;
196         hpa_t shadow_addr;
197         u64 *sptep;
198         int level;
199         unsigned index;
200 };
201
202 static const union kvm_mmu_page_role mmu_base_role_mask = {
203         .cr0_wp = 1,
204         .gpte_is_8_bytes = 1,
205         .nxe = 1,
206         .smep_andnot_wp = 1,
207         .smap_andnot_wp = 1,
208         .smm = 1,
209         .guest_mode = 1,
210         .ad_disabled = 1,
211 };
212
213 #define for_each_shadow_entry_using_root(_vcpu, _root, _addr, _walker)     \
214         for (shadow_walk_init_using_root(&(_walker), (_vcpu),              \
215                                          (_root), (_addr));                \
216              shadow_walk_okay(&(_walker));                                 \
217              shadow_walk_next(&(_walker)))
218
219 #define for_each_shadow_entry(_vcpu, _addr, _walker)            \
220         for (shadow_walk_init(&(_walker), _vcpu, _addr);        \
221              shadow_walk_okay(&(_walker));                      \
222              shadow_walk_next(&(_walker)))
223
224 #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte)     \
225         for (shadow_walk_init(&(_walker), _vcpu, _addr);                \
226              shadow_walk_okay(&(_walker)) &&                            \
227                 ({ spte = mmu_spte_get_lockless(_walker.sptep); 1; });  \
228              __shadow_walk_next(&(_walker), spte))
229
230 static struct kmem_cache *pte_list_desc_cache;
231 static struct kmem_cache *mmu_page_header_cache;
232 static struct percpu_counter kvm_total_used_mmu_pages;
233
234 static u64 __read_mostly shadow_nx_mask;
235 static u64 __read_mostly shadow_x_mask; /* mutual exclusive with nx_mask */
236 static u64 __read_mostly shadow_user_mask;
237 static u64 __read_mostly shadow_accessed_mask;
238 static u64 __read_mostly shadow_dirty_mask;
239 static u64 __read_mostly shadow_mmio_mask;
240 static u64 __read_mostly shadow_mmio_value;
241 static u64 __read_mostly shadow_mmio_access_mask;
242 static u64 __read_mostly shadow_present_mask;
243 static u64 __read_mostly shadow_me_mask;
244
245 /*
246  * SPTEs used by MMUs without A/D bits are marked with SPTE_AD_DISABLED_MASK;
247  * shadow_acc_track_mask is the set of bits to be cleared in non-accessed
248  * pages.
249  */
250 static u64 __read_mostly shadow_acc_track_mask;
251
252 /*
253  * The mask/shift to use for saving the original R/X bits when marking the PTE
254  * as not-present for access tracking purposes. We do not save the W bit as the
255  * PTEs being access tracked also need to be dirty tracked, so the W bit will be
256  * restored only when a write is attempted to the page.
257  */
258 static const u64 shadow_acc_track_saved_bits_mask = PT64_EPT_READABLE_MASK |
259                                                     PT64_EPT_EXECUTABLE_MASK;
260 static const u64 shadow_acc_track_saved_bits_shift = PT64_SECOND_AVAIL_BITS_SHIFT;
261
262 /*
263  * This mask must be set on all non-zero Non-Present or Reserved SPTEs in order
264  * to guard against L1TF attacks.
265  */
266 static u64 __read_mostly shadow_nonpresent_or_rsvd_mask;
267
268 /*
269  * The number of high-order 1 bits to use in the mask above.
270  */
271 static const u64 shadow_nonpresent_or_rsvd_mask_len = 5;
272
273 /*
274  * In some cases, we need to preserve the GFN of a non-present or reserved
275  * SPTE when we usurp the upper five bits of the physical address space to
276  * defend against L1TF, e.g. for MMIO SPTEs.  To preserve the GFN, we'll
277  * shift bits of the GFN that overlap with shadow_nonpresent_or_rsvd_mask
278  * left into the reserved bits, i.e. the GFN in the SPTE will be split into
279  * high and low parts.  This mask covers the lower bits of the GFN.
280  */
281 static u64 __read_mostly shadow_nonpresent_or_rsvd_lower_gfn_mask;
282
283 /*
284  * The number of non-reserved physical address bits irrespective of features
285  * that repurpose legal bits, e.g. MKTME.
286  */
287 static u8 __read_mostly shadow_phys_bits;
288
289 static void mmu_spte_set(u64 *sptep, u64 spte);
290 static bool is_executable_pte(u64 spte);
291 static union kvm_mmu_page_role
292 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu);
293
294 #define CREATE_TRACE_POINTS
295 #include "mmutrace.h"
296
297
298 static inline bool kvm_available_flush_tlb_with_range(void)
299 {
300         return kvm_x86_ops->tlb_remote_flush_with_range;
301 }
302
303 static void kvm_flush_remote_tlbs_with_range(struct kvm *kvm,
304                 struct kvm_tlb_range *range)
305 {
306         int ret = -ENOTSUPP;
307
308         if (range && kvm_x86_ops->tlb_remote_flush_with_range)
309                 ret = kvm_x86_ops->tlb_remote_flush_with_range(kvm, range);
310
311         if (ret)
312                 kvm_flush_remote_tlbs(kvm);
313 }
314
315 static void kvm_flush_remote_tlbs_with_address(struct kvm *kvm,
316                 u64 start_gfn, u64 pages)
317 {
318         struct kvm_tlb_range range;
319
320         range.start_gfn = start_gfn;
321         range.pages = pages;
322
323         kvm_flush_remote_tlbs_with_range(kvm, &range);
324 }
325
326 void kvm_mmu_set_mmio_spte_mask(u64 mmio_mask, u64 mmio_value, u64 access_mask)
327 {
328         BUG_ON((u64)(unsigned)access_mask != access_mask);
329         BUG_ON((mmio_mask & mmio_value) != mmio_value);
330         shadow_mmio_value = mmio_value | SPTE_MMIO_MASK;
331         shadow_mmio_mask = mmio_mask | SPTE_SPECIAL_MASK;
332         shadow_mmio_access_mask = access_mask;
333 }
334 EXPORT_SYMBOL_GPL(kvm_mmu_set_mmio_spte_mask);
335
336 static bool is_mmio_spte(u64 spte)
337 {
338         return (spte & shadow_mmio_mask) == shadow_mmio_value;
339 }
340
341 static inline bool sp_ad_disabled(struct kvm_mmu_page *sp)
342 {
343         return sp->role.ad_disabled;
344 }
345
346 static inline bool kvm_vcpu_ad_need_write_protect(struct kvm_vcpu *vcpu)
347 {
348         /*
349          * When using the EPT page-modification log, the GPAs in the log
350          * would come from L2 rather than L1.  Therefore, we need to rely
351          * on write protection to record dirty pages.  This also bypasses
352          * PML, since writes now result in a vmexit.
353          */
354         return vcpu->arch.mmu == &vcpu->arch.guest_mmu;
355 }
356
357 static inline bool spte_ad_enabled(u64 spte)
358 {
359         MMU_WARN_ON(is_mmio_spte(spte));
360         return (spte & SPTE_SPECIAL_MASK) != SPTE_AD_DISABLED_MASK;
361 }
362
363 static inline bool spte_ad_need_write_protect(u64 spte)
364 {
365         MMU_WARN_ON(is_mmio_spte(spte));
366         return (spte & SPTE_SPECIAL_MASK) != SPTE_AD_ENABLED_MASK;
367 }
368
369 static bool is_nx_huge_page_enabled(void)
370 {
371         return READ_ONCE(nx_huge_pages);
372 }
373
374 static inline u64 spte_shadow_accessed_mask(u64 spte)
375 {
376         MMU_WARN_ON(is_mmio_spte(spte));
377         return spte_ad_enabled(spte) ? shadow_accessed_mask : 0;
378 }
379
380 static inline u64 spte_shadow_dirty_mask(u64 spte)
381 {
382         MMU_WARN_ON(is_mmio_spte(spte));
383         return spte_ad_enabled(spte) ? shadow_dirty_mask : 0;
384 }
385
386 static inline bool is_access_track_spte(u64 spte)
387 {
388         return !spte_ad_enabled(spte) && (spte & shadow_acc_track_mask) == 0;
389 }
390
391 /*
392  * Due to limited space in PTEs, the MMIO generation is a 19 bit subset of
393  * the memslots generation and is derived as follows:
394  *
395  * Bits 0-8 of the MMIO generation are propagated to spte bits 3-11
396  * Bits 9-18 of the MMIO generation are propagated to spte bits 52-61
397  *
398  * The KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS flag is intentionally not included in
399  * the MMIO generation number, as doing so would require stealing a bit from
400  * the "real" generation number and thus effectively halve the maximum number
401  * of MMIO generations that can be handled before encountering a wrap (which
402  * requires a full MMU zap).  The flag is instead explicitly queried when
403  * checking for MMIO spte cache hits.
404  */
405 #define MMIO_SPTE_GEN_MASK              GENMASK_ULL(18, 0)
406
407 #define MMIO_SPTE_GEN_LOW_START         3
408 #define MMIO_SPTE_GEN_LOW_END           11
409 #define MMIO_SPTE_GEN_LOW_MASK          GENMASK_ULL(MMIO_SPTE_GEN_LOW_END, \
410                                                     MMIO_SPTE_GEN_LOW_START)
411
412 #define MMIO_SPTE_GEN_HIGH_START        52
413 #define MMIO_SPTE_GEN_HIGH_END          61
414 #define MMIO_SPTE_GEN_HIGH_MASK         GENMASK_ULL(MMIO_SPTE_GEN_HIGH_END, \
415                                                     MMIO_SPTE_GEN_HIGH_START)
416 static u64 generation_mmio_spte_mask(u64 gen)
417 {
418         u64 mask;
419
420         WARN_ON(gen & ~MMIO_SPTE_GEN_MASK);
421
422         mask = (gen << MMIO_SPTE_GEN_LOW_START) & MMIO_SPTE_GEN_LOW_MASK;
423         mask |= (gen << MMIO_SPTE_GEN_HIGH_START) & MMIO_SPTE_GEN_HIGH_MASK;
424         return mask;
425 }
426
427 static u64 get_mmio_spte_generation(u64 spte)
428 {
429         u64 gen;
430
431         spte &= ~shadow_mmio_mask;
432
433         gen = (spte & MMIO_SPTE_GEN_LOW_MASK) >> MMIO_SPTE_GEN_LOW_START;
434         gen |= (spte & MMIO_SPTE_GEN_HIGH_MASK) >> MMIO_SPTE_GEN_HIGH_START;
435         return gen;
436 }
437
438 static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
439                            unsigned access)
440 {
441         u64 gen = kvm_vcpu_memslots(vcpu)->generation & MMIO_SPTE_GEN_MASK;
442         u64 mask = generation_mmio_spte_mask(gen);
443         u64 gpa = gfn << PAGE_SHIFT;
444
445         access &= shadow_mmio_access_mask;
446         mask |= shadow_mmio_value | access;
447         mask |= gpa | shadow_nonpresent_or_rsvd_mask;
448         mask |= (gpa & shadow_nonpresent_or_rsvd_mask)
449                 << shadow_nonpresent_or_rsvd_mask_len;
450
451         trace_mark_mmio_spte(sptep, gfn, access, gen);
452         mmu_spte_set(sptep, mask);
453 }
454
455 static gfn_t get_mmio_spte_gfn(u64 spte)
456 {
457         u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
458
459         gpa |= (spte >> shadow_nonpresent_or_rsvd_mask_len)
460                & shadow_nonpresent_or_rsvd_mask;
461
462         return gpa >> PAGE_SHIFT;
463 }
464
465 static unsigned get_mmio_spte_access(u64 spte)
466 {
467         return spte & shadow_mmio_access_mask;
468 }
469
470 static bool set_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
471                           kvm_pfn_t pfn, unsigned access)
472 {
473         if (unlikely(is_noslot_pfn(pfn))) {
474                 mark_mmio_spte(vcpu, sptep, gfn, access);
475                 return true;
476         }
477
478         return false;
479 }
480
481 static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
482 {
483         u64 kvm_gen, spte_gen, gen;
484
485         gen = kvm_vcpu_memslots(vcpu)->generation;
486         if (unlikely(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS))
487                 return false;
488
489         kvm_gen = gen & MMIO_SPTE_GEN_MASK;
490         spte_gen = get_mmio_spte_generation(spte);
491
492         trace_check_mmio_spte(spte, kvm_gen, spte_gen);
493         return likely(kvm_gen == spte_gen);
494 }
495
496 /*
497  * Sets the shadow PTE masks used by the MMU.
498  *
499  * Assumptions:
500  *  - Setting either @accessed_mask or @dirty_mask requires setting both
501  *  - At least one of @accessed_mask or @acc_track_mask must be set
502  */
503 void kvm_mmu_set_mask_ptes(u64 user_mask, u64 accessed_mask,
504                 u64 dirty_mask, u64 nx_mask, u64 x_mask, u64 p_mask,
505                 u64 acc_track_mask, u64 me_mask)
506 {
507         BUG_ON(!dirty_mask != !accessed_mask);
508         BUG_ON(!accessed_mask && !acc_track_mask);
509         BUG_ON(acc_track_mask & SPTE_SPECIAL_MASK);
510
511         shadow_user_mask = user_mask;
512         shadow_accessed_mask = accessed_mask;
513         shadow_dirty_mask = dirty_mask;
514         shadow_nx_mask = nx_mask;
515         shadow_x_mask = x_mask;
516         shadow_present_mask = p_mask;
517         shadow_acc_track_mask = acc_track_mask;
518         shadow_me_mask = me_mask;
519 }
520 EXPORT_SYMBOL_GPL(kvm_mmu_set_mask_ptes);
521
522 static u8 kvm_get_shadow_phys_bits(void)
523 {
524         /*
525          * boot_cpu_data.x86_phys_bits is reduced when MKTME is detected
526          * in CPU detection code, but MKTME treats those reduced bits as
527          * 'keyID' thus they are not reserved bits. Therefore for MKTME
528          * we should still return physical address bits reported by CPUID.
529          */
530         if (!boot_cpu_has(X86_FEATURE_TME) ||
531             WARN_ON_ONCE(boot_cpu_data.extended_cpuid_level < 0x80000008))
532                 return boot_cpu_data.x86_phys_bits;
533
534         return cpuid_eax(0x80000008) & 0xff;
535 }
536
537 static void kvm_mmu_reset_all_pte_masks(void)
538 {
539         u8 low_phys_bits;
540
541         shadow_user_mask = 0;
542         shadow_accessed_mask = 0;
543         shadow_dirty_mask = 0;
544         shadow_nx_mask = 0;
545         shadow_x_mask = 0;
546         shadow_mmio_mask = 0;
547         shadow_present_mask = 0;
548         shadow_acc_track_mask = 0;
549
550         shadow_phys_bits = kvm_get_shadow_phys_bits();
551
552         /*
553          * If the CPU has 46 or less physical address bits, then set an
554          * appropriate mask to guard against L1TF attacks. Otherwise, it is
555          * assumed that the CPU is not vulnerable to L1TF.
556          *
557          * Some Intel CPUs address the L1 cache using more PA bits than are
558          * reported by CPUID. Use the PA width of the L1 cache when possible
559          * to achieve more effective mitigation, e.g. if system RAM overlaps
560          * the most significant bits of legal physical address space.
561          */
562         shadow_nonpresent_or_rsvd_mask = 0;
563         low_phys_bits = boot_cpu_data.x86_cache_bits;
564         if (boot_cpu_data.x86_cache_bits <
565             52 - shadow_nonpresent_or_rsvd_mask_len) {
566                 shadow_nonpresent_or_rsvd_mask =
567                         rsvd_bits(boot_cpu_data.x86_cache_bits -
568                                   shadow_nonpresent_or_rsvd_mask_len,
569                                   boot_cpu_data.x86_cache_bits - 1);
570                 low_phys_bits -= shadow_nonpresent_or_rsvd_mask_len;
571         } else
572                 WARN_ON_ONCE(boot_cpu_has_bug(X86_BUG_L1TF));
573
574         shadow_nonpresent_or_rsvd_lower_gfn_mask =
575                 GENMASK_ULL(low_phys_bits - 1, PAGE_SHIFT);
576 }
577
578 static int is_cpuid_PSE36(void)
579 {
580         return 1;
581 }
582
583 static int is_nx(struct kvm_vcpu *vcpu)
584 {
585         return vcpu->arch.efer & EFER_NX;
586 }
587
588 static int is_shadow_present_pte(u64 pte)
589 {
590         return (pte != 0) && !is_mmio_spte(pte);
591 }
592
593 static int is_large_pte(u64 pte)
594 {
595         return pte & PT_PAGE_SIZE_MASK;
596 }
597
598 static int is_last_spte(u64 pte, int level)
599 {
600         if (level == PT_PAGE_TABLE_LEVEL)
601                 return 1;
602         if (is_large_pte(pte))
603                 return 1;
604         return 0;
605 }
606
607 static bool is_executable_pte(u64 spte)
608 {
609         return (spte & (shadow_x_mask | shadow_nx_mask)) == shadow_x_mask;
610 }
611
612 static kvm_pfn_t spte_to_pfn(u64 pte)
613 {
614         return (pte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT;
615 }
616
617 static gfn_t pse36_gfn_delta(u32 gpte)
618 {
619         int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT;
620
621         return (gpte & PT32_DIR_PSE36_MASK) << shift;
622 }
623
624 #ifdef CONFIG_X86_64
625 static void __set_spte(u64 *sptep, u64 spte)
626 {
627         WRITE_ONCE(*sptep, spte);
628 }
629
630 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
631 {
632         WRITE_ONCE(*sptep, spte);
633 }
634
635 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
636 {
637         return xchg(sptep, spte);
638 }
639
640 static u64 __get_spte_lockless(u64 *sptep)
641 {
642         return READ_ONCE(*sptep);
643 }
644 #else
645 union split_spte {
646         struct {
647                 u32 spte_low;
648                 u32 spte_high;
649         };
650         u64 spte;
651 };
652
653 static void count_spte_clear(u64 *sptep, u64 spte)
654 {
655         struct kvm_mmu_page *sp =  page_header(__pa(sptep));
656
657         if (is_shadow_present_pte(spte))
658                 return;
659
660         /* Ensure the spte is completely set before we increase the count */
661         smp_wmb();
662         sp->clear_spte_count++;
663 }
664
665 static void __set_spte(u64 *sptep, u64 spte)
666 {
667         union split_spte *ssptep, sspte;
668
669         ssptep = (union split_spte *)sptep;
670         sspte = (union split_spte)spte;
671
672         ssptep->spte_high = sspte.spte_high;
673
674         /*
675          * If we map the spte from nonpresent to present, We should store
676          * the high bits firstly, then set present bit, so cpu can not
677          * fetch this spte while we are setting the spte.
678          */
679         smp_wmb();
680
681         WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
682 }
683
684 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
685 {
686         union split_spte *ssptep, sspte;
687
688         ssptep = (union split_spte *)sptep;
689         sspte = (union split_spte)spte;
690
691         WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
692
693         /*
694          * If we map the spte from present to nonpresent, we should clear
695          * present bit firstly to avoid vcpu fetch the old high bits.
696          */
697         smp_wmb();
698
699         ssptep->spte_high = sspte.spte_high;
700         count_spte_clear(sptep, spte);
701 }
702
703 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
704 {
705         union split_spte *ssptep, sspte, orig;
706
707         ssptep = (union split_spte *)sptep;
708         sspte = (union split_spte)spte;
709
710         /* xchg acts as a barrier before the setting of the high bits */
711         orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
712         orig.spte_high = ssptep->spte_high;
713         ssptep->spte_high = sspte.spte_high;
714         count_spte_clear(sptep, spte);
715
716         return orig.spte;
717 }
718
719 /*
720  * The idea using the light way get the spte on x86_32 guest is from
721  * gup_get_pte (mm/gup.c).
722  *
723  * An spte tlb flush may be pending, because kvm_set_pte_rmapp
724  * coalesces them and we are running out of the MMU lock.  Therefore
725  * we need to protect against in-progress updates of the spte.
726  *
727  * Reading the spte while an update is in progress may get the old value
728  * for the high part of the spte.  The race is fine for a present->non-present
729  * change (because the high part of the spte is ignored for non-present spte),
730  * but for a present->present change we must reread the spte.
731  *
732  * All such changes are done in two steps (present->non-present and
733  * non-present->present), hence it is enough to count the number of
734  * present->non-present updates: if it changed while reading the spte,
735  * we might have hit the race.  This is done using clear_spte_count.
736  */
737 static u64 __get_spte_lockless(u64 *sptep)
738 {
739         struct kvm_mmu_page *sp =  page_header(__pa(sptep));
740         union split_spte spte, *orig = (union split_spte *)sptep;
741         int count;
742
743 retry:
744         count = sp->clear_spte_count;
745         smp_rmb();
746
747         spte.spte_low = orig->spte_low;
748         smp_rmb();
749
750         spte.spte_high = orig->spte_high;
751         smp_rmb();
752
753         if (unlikely(spte.spte_low != orig->spte_low ||
754               count != sp->clear_spte_count))
755                 goto retry;
756
757         return spte.spte;
758 }
759 #endif
760
761 static bool spte_can_locklessly_be_made_writable(u64 spte)
762 {
763         return (spte & (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE)) ==
764                 (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE);
765 }
766
767 static bool spte_has_volatile_bits(u64 spte)
768 {
769         if (!is_shadow_present_pte(spte))
770                 return false;
771
772         /*
773          * Always atomically update spte if it can be updated
774          * out of mmu-lock, it can ensure dirty bit is not lost,
775          * also, it can help us to get a stable is_writable_pte()
776          * to ensure tlb flush is not missed.
777          */
778         if (spte_can_locklessly_be_made_writable(spte) ||
779             is_access_track_spte(spte))
780                 return true;
781
782         if (spte_ad_enabled(spte)) {
783                 if ((spte & shadow_accessed_mask) == 0 ||
784                     (is_writable_pte(spte) && (spte & shadow_dirty_mask) == 0))
785                         return true;
786         }
787
788         return false;
789 }
790
791 static bool is_accessed_spte(u64 spte)
792 {
793         u64 accessed_mask = spte_shadow_accessed_mask(spte);
794
795         return accessed_mask ? spte & accessed_mask
796                              : !is_access_track_spte(spte);
797 }
798
799 static bool is_dirty_spte(u64 spte)
800 {
801         u64 dirty_mask = spte_shadow_dirty_mask(spte);
802
803         return dirty_mask ? spte & dirty_mask : spte & PT_WRITABLE_MASK;
804 }
805
806 /* Rules for using mmu_spte_set:
807  * Set the sptep from nonpresent to present.
808  * Note: the sptep being assigned *must* be either not present
809  * or in a state where the hardware will not attempt to update
810  * the spte.
811  */
812 static void mmu_spte_set(u64 *sptep, u64 new_spte)
813 {
814         WARN_ON(is_shadow_present_pte(*sptep));
815         __set_spte(sptep, new_spte);
816 }
817
818 /*
819  * Update the SPTE (excluding the PFN), but do not track changes in its
820  * accessed/dirty status.
821  */
822 static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
823 {
824         u64 old_spte = *sptep;
825
826         WARN_ON(!is_shadow_present_pte(new_spte));
827
828         if (!is_shadow_present_pte(old_spte)) {
829                 mmu_spte_set(sptep, new_spte);
830                 return old_spte;
831         }
832
833         if (!spte_has_volatile_bits(old_spte))
834                 __update_clear_spte_fast(sptep, new_spte);
835         else
836                 old_spte = __update_clear_spte_slow(sptep, new_spte);
837
838         WARN_ON(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
839
840         return old_spte;
841 }
842
843 /* Rules for using mmu_spte_update:
844  * Update the state bits, it means the mapped pfn is not changed.
845  *
846  * Whenever we overwrite a writable spte with a read-only one we
847  * should flush remote TLBs. Otherwise rmap_write_protect
848  * will find a read-only spte, even though the writable spte
849  * might be cached on a CPU's TLB, the return value indicates this
850  * case.
851  *
852  * Returns true if the TLB needs to be flushed
853  */
854 static bool mmu_spte_update(u64 *sptep, u64 new_spte)
855 {
856         bool flush = false;
857         u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
858
859         if (!is_shadow_present_pte(old_spte))
860                 return false;
861
862         /*
863          * For the spte updated out of mmu-lock is safe, since
864          * we always atomically update it, see the comments in
865          * spte_has_volatile_bits().
866          */
867         if (spte_can_locklessly_be_made_writable(old_spte) &&
868               !is_writable_pte(new_spte))
869                 flush = true;
870
871         /*
872          * Flush TLB when accessed/dirty states are changed in the page tables,
873          * to guarantee consistency between TLB and page tables.
874          */
875
876         if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
877                 flush = true;
878                 kvm_set_pfn_accessed(spte_to_pfn(old_spte));
879         }
880
881         if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
882                 flush = true;
883                 kvm_set_pfn_dirty(spte_to_pfn(old_spte));
884         }
885
886         return flush;
887 }
888
889 /*
890  * Rules for using mmu_spte_clear_track_bits:
891  * It sets the sptep from present to nonpresent, and track the
892  * state bits, it is used to clear the last level sptep.
893  * Returns non-zero if the PTE was previously valid.
894  */
895 static int mmu_spte_clear_track_bits(u64 *sptep)
896 {
897         kvm_pfn_t pfn;
898         u64 old_spte = *sptep;
899
900         if (!spte_has_volatile_bits(old_spte))
901                 __update_clear_spte_fast(sptep, 0ull);
902         else
903                 old_spte = __update_clear_spte_slow(sptep, 0ull);
904
905         if (!is_shadow_present_pte(old_spte))
906                 return 0;
907
908         pfn = spte_to_pfn(old_spte);
909
910         /*
911          * KVM does not hold the refcount of the page used by
912          * kvm mmu, before reclaiming the page, we should
913          * unmap it from mmu first.
914          */
915         WARN_ON(!kvm_is_reserved_pfn(pfn) && !page_count(pfn_to_page(pfn)));
916
917         if (is_accessed_spte(old_spte))
918                 kvm_set_pfn_accessed(pfn);
919
920         if (is_dirty_spte(old_spte))
921                 kvm_set_pfn_dirty(pfn);
922
923         return 1;
924 }
925
926 /*
927  * Rules for using mmu_spte_clear_no_track:
928  * Directly clear spte without caring the state bits of sptep,
929  * it is used to set the upper level spte.
930  */
931 static void mmu_spte_clear_no_track(u64 *sptep)
932 {
933         __update_clear_spte_fast(sptep, 0ull);
934 }
935
936 static u64 mmu_spte_get_lockless(u64 *sptep)
937 {
938         return __get_spte_lockless(sptep);
939 }
940
941 static u64 mark_spte_for_access_track(u64 spte)
942 {
943         if (spte_ad_enabled(spte))
944                 return spte & ~shadow_accessed_mask;
945
946         if (is_access_track_spte(spte))
947                 return spte;
948
949         /*
950          * Making an Access Tracking PTE will result in removal of write access
951          * from the PTE. So, verify that we will be able to restore the write
952          * access in the fast page fault path later on.
953          */
954         WARN_ONCE((spte & PT_WRITABLE_MASK) &&
955                   !spte_can_locklessly_be_made_writable(spte),
956                   "kvm: Writable SPTE is not locklessly dirty-trackable\n");
957
958         WARN_ONCE(spte & (shadow_acc_track_saved_bits_mask <<
959                           shadow_acc_track_saved_bits_shift),
960                   "kvm: Access Tracking saved bit locations are not zero\n");
961
962         spte |= (spte & shadow_acc_track_saved_bits_mask) <<
963                 shadow_acc_track_saved_bits_shift;
964         spte &= ~shadow_acc_track_mask;
965
966         return spte;
967 }
968
969 /* Restore an acc-track PTE back to a regular PTE */
970 static u64 restore_acc_track_spte(u64 spte)
971 {
972         u64 new_spte = spte;
973         u64 saved_bits = (spte >> shadow_acc_track_saved_bits_shift)
974                          & shadow_acc_track_saved_bits_mask;
975
976         WARN_ON_ONCE(spte_ad_enabled(spte));
977         WARN_ON_ONCE(!is_access_track_spte(spte));
978
979         new_spte &= ~shadow_acc_track_mask;
980         new_spte &= ~(shadow_acc_track_saved_bits_mask <<
981                       shadow_acc_track_saved_bits_shift);
982         new_spte |= saved_bits;
983
984         return new_spte;
985 }
986
987 /* Returns the Accessed status of the PTE and resets it at the same time. */
988 static bool mmu_spte_age(u64 *sptep)
989 {
990         u64 spte = mmu_spte_get_lockless(sptep);
991
992         if (!is_accessed_spte(spte))
993                 return false;
994
995         if (spte_ad_enabled(spte)) {
996                 clear_bit((ffs(shadow_accessed_mask) - 1),
997                           (unsigned long *)sptep);
998         } else {
999                 /*
1000                  * Capture the dirty status of the page, so that it doesn't get
1001                  * lost when the SPTE is marked for access tracking.
1002                  */
1003                 if (is_writable_pte(spte))
1004                         kvm_set_pfn_dirty(spte_to_pfn(spte));
1005
1006                 spte = mark_spte_for_access_track(spte);
1007                 mmu_spte_update_no_track(sptep, spte);
1008         }
1009
1010         return true;
1011 }
1012
1013 static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
1014 {
1015         /*
1016          * Prevent page table teardown by making any free-er wait during
1017          * kvm_flush_remote_tlbs() IPI to all active vcpus.
1018          */
1019         local_irq_disable();
1020
1021         /*
1022          * Make sure a following spte read is not reordered ahead of the write
1023          * to vcpu->mode.
1024          */
1025         smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
1026 }
1027
1028 static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
1029 {
1030         /*
1031          * Make sure the write to vcpu->mode is not reordered in front of
1032          * reads to sptes.  If it does, kvm_mmu_commit_zap_page() can see us
1033          * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
1034          */
1035         smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
1036         local_irq_enable();
1037 }
1038
1039 static int mmu_topup_memory_cache(struct kvm_mmu_memory_cache *cache,
1040                                   struct kmem_cache *base_cache, int min)
1041 {
1042         void *obj;
1043
1044         if (cache->nobjs >= min)
1045                 return 0;
1046         while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
1047                 obj = kmem_cache_zalloc(base_cache, GFP_KERNEL_ACCOUNT);
1048                 if (!obj)
1049                         return cache->nobjs >= min ? 0 : -ENOMEM;
1050                 cache->objects[cache->nobjs++] = obj;
1051         }
1052         return 0;
1053 }
1054
1055 static int mmu_memory_cache_free_objects(struct kvm_mmu_memory_cache *cache)
1056 {
1057         return cache->nobjs;
1058 }
1059
1060 static void mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc,
1061                                   struct kmem_cache *cache)
1062 {
1063         while (mc->nobjs)
1064                 kmem_cache_free(cache, mc->objects[--mc->nobjs]);
1065 }
1066
1067 static int mmu_topup_memory_cache_page(struct kvm_mmu_memory_cache *cache,
1068                                        int min)
1069 {
1070         void *page;
1071
1072         if (cache->nobjs >= min)
1073                 return 0;
1074         while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
1075                 page = (void *)__get_free_page(GFP_KERNEL_ACCOUNT);
1076                 if (!page)
1077                         return cache->nobjs >= min ? 0 : -ENOMEM;
1078                 cache->objects[cache->nobjs++] = page;
1079         }
1080         return 0;
1081 }
1082
1083 static void mmu_free_memory_cache_page(struct kvm_mmu_memory_cache *mc)
1084 {
1085         while (mc->nobjs)
1086                 free_page((unsigned long)mc->objects[--mc->nobjs]);
1087 }
1088
1089 static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu)
1090 {
1091         int r;
1092
1093         r = mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
1094                                    pte_list_desc_cache, 8 + PTE_PREFETCH_NUM);
1095         if (r)
1096                 goto out;
1097         r = mmu_topup_memory_cache_page(&vcpu->arch.mmu_page_cache, 8);
1098         if (r)
1099                 goto out;
1100         r = mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
1101                                    mmu_page_header_cache, 4);
1102 out:
1103         return r;
1104 }
1105
1106 static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
1107 {
1108         mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
1109                                 pte_list_desc_cache);
1110         mmu_free_memory_cache_page(&vcpu->arch.mmu_page_cache);
1111         mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache,
1112                                 mmu_page_header_cache);
1113 }
1114
1115 static void *mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
1116 {
1117         void *p;
1118
1119         BUG_ON(!mc->nobjs);
1120         p = mc->objects[--mc->nobjs];
1121         return p;
1122 }
1123
1124 static struct pte_list_desc *mmu_alloc_pte_list_desc(struct kvm_vcpu *vcpu)
1125 {
1126         return mmu_memory_cache_alloc(&vcpu->arch.mmu_pte_list_desc_cache);
1127 }
1128
1129 static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
1130 {
1131         kmem_cache_free(pte_list_desc_cache, pte_list_desc);
1132 }
1133
1134 static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
1135 {
1136         if (!sp->role.direct)
1137                 return sp->gfns[index];
1138
1139         return sp->gfn + (index << ((sp->role.level - 1) * PT64_LEVEL_BITS));
1140 }
1141
1142 static void kvm_mmu_page_set_gfn(struct kvm_mmu_page *sp, int index, gfn_t gfn)
1143 {
1144         if (!sp->role.direct) {
1145                 sp->gfns[index] = gfn;
1146                 return;
1147         }
1148
1149         if (WARN_ON(gfn != kvm_mmu_page_get_gfn(sp, index)))
1150                 pr_err_ratelimited("gfn mismatch under direct page %llx "
1151                                    "(expected %llx, got %llx)\n",
1152                                    sp->gfn,
1153                                    kvm_mmu_page_get_gfn(sp, index), gfn);
1154 }
1155
1156 /*
1157  * Return the pointer to the large page information for a given gfn,
1158  * handling slots that are not large page aligned.
1159  */
1160 static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
1161                                               struct kvm_memory_slot *slot,
1162                                               int level)
1163 {
1164         unsigned long idx;
1165
1166         idx = gfn_to_index(gfn, slot->base_gfn, level);
1167         return &slot->arch.lpage_info[level - 2][idx];
1168 }
1169
1170 static void update_gfn_disallow_lpage_count(struct kvm_memory_slot *slot,
1171                                             gfn_t gfn, int count)
1172 {
1173         struct kvm_lpage_info *linfo;
1174         int i;
1175
1176         for (i = PT_DIRECTORY_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1177                 linfo = lpage_info_slot(gfn, slot, i);
1178                 linfo->disallow_lpage += count;
1179                 WARN_ON(linfo->disallow_lpage < 0);
1180         }
1181 }
1182
1183 void kvm_mmu_gfn_disallow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
1184 {
1185         update_gfn_disallow_lpage_count(slot, gfn, 1);
1186 }
1187
1188 void kvm_mmu_gfn_allow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
1189 {
1190         update_gfn_disallow_lpage_count(slot, gfn, -1);
1191 }
1192
1193 static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
1194 {
1195         struct kvm_memslots *slots;
1196         struct kvm_memory_slot *slot;
1197         gfn_t gfn;
1198
1199         kvm->arch.indirect_shadow_pages++;
1200         gfn = sp->gfn;
1201         slots = kvm_memslots_for_spte_role(kvm, sp->role);
1202         slot = __gfn_to_memslot(slots, gfn);
1203
1204         /* the non-leaf shadow pages are keeping readonly. */
1205         if (sp->role.level > PT_PAGE_TABLE_LEVEL)
1206                 return kvm_slot_page_track_add_page(kvm, slot, gfn,
1207                                                     KVM_PAGE_TRACK_WRITE);
1208
1209         kvm_mmu_gfn_disallow_lpage(slot, gfn);
1210 }
1211
1212 static void account_huge_nx_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1213 {
1214         if (sp->lpage_disallowed)
1215                 return;
1216
1217         ++kvm->stat.nx_lpage_splits;
1218         sp->lpage_disallowed = true;
1219 }
1220
1221 static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
1222 {
1223         struct kvm_memslots *slots;
1224         struct kvm_memory_slot *slot;
1225         gfn_t gfn;
1226
1227         kvm->arch.indirect_shadow_pages--;
1228         gfn = sp->gfn;
1229         slots = kvm_memslots_for_spte_role(kvm, sp->role);
1230         slot = __gfn_to_memslot(slots, gfn);
1231         if (sp->role.level > PT_PAGE_TABLE_LEVEL)
1232                 return kvm_slot_page_track_remove_page(kvm, slot, gfn,
1233                                                        KVM_PAGE_TRACK_WRITE);
1234
1235         kvm_mmu_gfn_allow_lpage(slot, gfn);
1236 }
1237
1238 static void unaccount_huge_nx_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1239 {
1240         --kvm->stat.nx_lpage_splits;
1241         sp->lpage_disallowed = false;
1242 }
1243
1244 static bool __mmu_gfn_lpage_is_disallowed(gfn_t gfn, int level,
1245                                           struct kvm_memory_slot *slot)
1246 {
1247         struct kvm_lpage_info *linfo;
1248
1249         if (slot) {
1250                 linfo = lpage_info_slot(gfn, slot, level);
1251                 return !!linfo->disallow_lpage;
1252         }
1253
1254         return true;
1255 }
1256
1257 static bool mmu_gfn_lpage_is_disallowed(struct kvm_vcpu *vcpu, gfn_t gfn,
1258                                         int level)
1259 {
1260         struct kvm_memory_slot *slot;
1261
1262         slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1263         return __mmu_gfn_lpage_is_disallowed(gfn, level, slot);
1264 }
1265
1266 static int host_mapping_level(struct kvm *kvm, gfn_t gfn)
1267 {
1268         unsigned long page_size;
1269         int i, ret = 0;
1270
1271         page_size = kvm_host_page_size(kvm, gfn);
1272
1273         for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1274                 if (page_size >= KVM_HPAGE_SIZE(i))
1275                         ret = i;
1276                 else
1277                         break;
1278         }
1279
1280         return ret;
1281 }
1282
1283 static inline bool memslot_valid_for_gpte(struct kvm_memory_slot *slot,
1284                                           bool no_dirty_log)
1285 {
1286         if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1287                 return false;
1288         if (no_dirty_log && slot->dirty_bitmap)
1289                 return false;
1290
1291         return true;
1292 }
1293
1294 static struct kvm_memory_slot *
1295 gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn,
1296                             bool no_dirty_log)
1297 {
1298         struct kvm_memory_slot *slot;
1299
1300         slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1301         if (!memslot_valid_for_gpte(slot, no_dirty_log))
1302                 slot = NULL;
1303
1304         return slot;
1305 }
1306
1307 static int mapping_level(struct kvm_vcpu *vcpu, gfn_t large_gfn,
1308                          bool *force_pt_level)
1309 {
1310         int host_level, level, max_level;
1311         struct kvm_memory_slot *slot;
1312
1313         if (unlikely(*force_pt_level))
1314                 return PT_PAGE_TABLE_LEVEL;
1315
1316         slot = kvm_vcpu_gfn_to_memslot(vcpu, large_gfn);
1317         *force_pt_level = !memslot_valid_for_gpte(slot, true);
1318         if (unlikely(*force_pt_level))
1319                 return PT_PAGE_TABLE_LEVEL;
1320
1321         host_level = host_mapping_level(vcpu->kvm, large_gfn);
1322
1323         if (host_level == PT_PAGE_TABLE_LEVEL)
1324                 return host_level;
1325
1326         max_level = min(kvm_x86_ops->get_lpage_level(), host_level);
1327
1328         for (level = PT_DIRECTORY_LEVEL; level <= max_level; ++level)
1329                 if (__mmu_gfn_lpage_is_disallowed(large_gfn, level, slot))
1330                         break;
1331
1332         return level - 1;
1333 }
1334
1335 /*
1336  * About rmap_head encoding:
1337  *
1338  * If the bit zero of rmap_head->val is clear, then it points to the only spte
1339  * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
1340  * pte_list_desc containing more mappings.
1341  */
1342
1343 /*
1344  * Returns the number of pointers in the rmap chain, not counting the new one.
1345  */
1346 static int pte_list_add(struct kvm_vcpu *vcpu, u64 *spte,
1347                         struct kvm_rmap_head *rmap_head)
1348 {
1349         struct pte_list_desc *desc;
1350         int i, count = 0;
1351
1352         if (!rmap_head->val) {
1353                 rmap_printk("pte_list_add: %p %llx 0->1\n", spte, *spte);
1354                 rmap_head->val = (unsigned long)spte;
1355         } else if (!(rmap_head->val & 1)) {
1356                 rmap_printk("pte_list_add: %p %llx 1->many\n", spte, *spte);
1357                 desc = mmu_alloc_pte_list_desc(vcpu);
1358                 desc->sptes[0] = (u64 *)rmap_head->val;
1359                 desc->sptes[1] = spte;
1360                 rmap_head->val = (unsigned long)desc | 1;
1361                 ++count;
1362         } else {
1363                 rmap_printk("pte_list_add: %p %llx many->many\n", spte, *spte);
1364                 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1365                 while (desc->sptes[PTE_LIST_EXT-1] && desc->more) {
1366                         desc = desc->more;
1367                         count += PTE_LIST_EXT;
1368                 }
1369                 if (desc->sptes[PTE_LIST_EXT-1]) {
1370                         desc->more = mmu_alloc_pte_list_desc(vcpu);
1371                         desc = desc->more;
1372                 }
1373                 for (i = 0; desc->sptes[i]; ++i)
1374                         ++count;
1375                 desc->sptes[i] = spte;
1376         }
1377         return count;
1378 }
1379
1380 static void
1381 pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
1382                            struct pte_list_desc *desc, int i,
1383                            struct pte_list_desc *prev_desc)
1384 {
1385         int j;
1386
1387         for (j = PTE_LIST_EXT - 1; !desc->sptes[j] && j > i; --j)
1388                 ;
1389         desc->sptes[i] = desc->sptes[j];
1390         desc->sptes[j] = NULL;
1391         if (j != 0)
1392                 return;
1393         if (!prev_desc && !desc->more)
1394                 rmap_head->val = (unsigned long)desc->sptes[0];
1395         else
1396                 if (prev_desc)
1397                         prev_desc->more = desc->more;
1398                 else
1399                         rmap_head->val = (unsigned long)desc->more | 1;
1400         mmu_free_pte_list_desc(desc);
1401 }
1402
1403 static void __pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
1404 {
1405         struct pte_list_desc *desc;
1406         struct pte_list_desc *prev_desc;
1407         int i;
1408
1409         if (!rmap_head->val) {
1410                 pr_err("%s: %p 0->BUG\n", __func__, spte);
1411                 BUG();
1412         } else if (!(rmap_head->val & 1)) {
1413                 rmap_printk("%s:  %p 1->0\n", __func__, spte);
1414                 if ((u64 *)rmap_head->val != spte) {
1415                         pr_err("%s:  %p 1->BUG\n", __func__, spte);
1416                         BUG();
1417                 }
1418                 rmap_head->val = 0;
1419         } else {
1420                 rmap_printk("%s:  %p many->many\n", __func__, spte);
1421                 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1422                 prev_desc = NULL;
1423                 while (desc) {
1424                         for (i = 0; i < PTE_LIST_EXT && desc->sptes[i]; ++i) {
1425                                 if (desc->sptes[i] == spte) {
1426                                         pte_list_desc_remove_entry(rmap_head,
1427                                                         desc, i, prev_desc);
1428                                         return;
1429                                 }
1430                         }
1431                         prev_desc = desc;
1432                         desc = desc->more;
1433                 }
1434                 pr_err("%s: %p many->many\n", __func__, spte);
1435                 BUG();
1436         }
1437 }
1438
1439 static void pte_list_remove(struct kvm_rmap_head *rmap_head, u64 *sptep)
1440 {
1441         mmu_spte_clear_track_bits(sptep);
1442         __pte_list_remove(sptep, rmap_head);
1443 }
1444
1445 static struct kvm_rmap_head *__gfn_to_rmap(gfn_t gfn, int level,
1446                                            struct kvm_memory_slot *slot)
1447 {
1448         unsigned long idx;
1449
1450         idx = gfn_to_index(gfn, slot->base_gfn, level);
1451         return &slot->arch.rmap[level - PT_PAGE_TABLE_LEVEL][idx];
1452 }
1453
1454 static struct kvm_rmap_head *gfn_to_rmap(struct kvm *kvm, gfn_t gfn,
1455                                          struct kvm_mmu_page *sp)
1456 {
1457         struct kvm_memslots *slots;
1458         struct kvm_memory_slot *slot;
1459
1460         slots = kvm_memslots_for_spte_role(kvm, sp->role);
1461         slot = __gfn_to_memslot(slots, gfn);
1462         return __gfn_to_rmap(gfn, sp->role.level, slot);
1463 }
1464
1465 static bool rmap_can_add(struct kvm_vcpu *vcpu)
1466 {
1467         struct kvm_mmu_memory_cache *cache;
1468
1469         cache = &vcpu->arch.mmu_pte_list_desc_cache;
1470         return mmu_memory_cache_free_objects(cache);
1471 }
1472
1473 static int rmap_add(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
1474 {
1475         struct kvm_mmu_page *sp;
1476         struct kvm_rmap_head *rmap_head;
1477
1478         sp = page_header(__pa(spte));
1479         kvm_mmu_page_set_gfn(sp, spte - sp->spt, gfn);
1480         rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
1481         return pte_list_add(vcpu, spte, rmap_head);
1482 }
1483
1484 static void rmap_remove(struct kvm *kvm, u64 *spte)
1485 {
1486         struct kvm_mmu_page *sp;
1487         gfn_t gfn;
1488         struct kvm_rmap_head *rmap_head;
1489
1490         sp = page_header(__pa(spte));
1491         gfn = kvm_mmu_page_get_gfn(sp, spte - sp->spt);
1492         rmap_head = gfn_to_rmap(kvm, gfn, sp);
1493         __pte_list_remove(spte, rmap_head);
1494 }
1495
1496 /*
1497  * Used by the following functions to iterate through the sptes linked by a
1498  * rmap.  All fields are private and not assumed to be used outside.
1499  */
1500 struct rmap_iterator {
1501         /* private fields */
1502         struct pte_list_desc *desc;     /* holds the sptep if not NULL */
1503         int pos;                        /* index of the sptep */
1504 };
1505
1506 /*
1507  * Iteration must be started by this function.  This should also be used after
1508  * removing/dropping sptes from the rmap link because in such cases the
1509  * information in the itererator may not be valid.
1510  *
1511  * Returns sptep if found, NULL otherwise.
1512  */
1513 static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1514                            struct rmap_iterator *iter)
1515 {
1516         u64 *sptep;
1517
1518         if (!rmap_head->val)
1519                 return NULL;
1520
1521         if (!(rmap_head->val & 1)) {
1522                 iter->desc = NULL;
1523                 sptep = (u64 *)rmap_head->val;
1524                 goto out;
1525         }
1526
1527         iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1528         iter->pos = 0;
1529         sptep = iter->desc->sptes[iter->pos];
1530 out:
1531         BUG_ON(!is_shadow_present_pte(*sptep));
1532         return sptep;
1533 }
1534
1535 /*
1536  * Must be used with a valid iterator: e.g. after rmap_get_first().
1537  *
1538  * Returns sptep if found, NULL otherwise.
1539  */
1540 static u64 *rmap_get_next(struct rmap_iterator *iter)
1541 {
1542         u64 *sptep;
1543
1544         if (iter->desc) {
1545                 if (iter->pos < PTE_LIST_EXT - 1) {
1546                         ++iter->pos;
1547                         sptep = iter->desc->sptes[iter->pos];
1548                         if (sptep)
1549                                 goto out;
1550                 }
1551
1552                 iter->desc = iter->desc->more;
1553
1554                 if (iter->desc) {
1555                         iter->pos = 0;
1556                         /* desc->sptes[0] cannot be NULL */
1557                         sptep = iter->desc->sptes[iter->pos];
1558                         goto out;
1559                 }
1560         }
1561
1562         return NULL;
1563 out:
1564         BUG_ON(!is_shadow_present_pte(*sptep));
1565         return sptep;
1566 }
1567
1568 #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_)                 \
1569         for (_spte_ = rmap_get_first(_rmap_head_, _iter_);              \
1570              _spte_; _spte_ = rmap_get_next(_iter_))
1571
1572 static void drop_spte(struct kvm *kvm, u64 *sptep)
1573 {
1574         if (mmu_spte_clear_track_bits(sptep))
1575                 rmap_remove(kvm, sptep);
1576 }
1577
1578
1579 static bool __drop_large_spte(struct kvm *kvm, u64 *sptep)
1580 {
1581         if (is_large_pte(*sptep)) {
1582                 WARN_ON(page_header(__pa(sptep))->role.level ==
1583                         PT_PAGE_TABLE_LEVEL);
1584                 drop_spte(kvm, sptep);
1585                 --kvm->stat.lpages;
1586                 return true;
1587         }
1588
1589         return false;
1590 }
1591
1592 static void drop_large_spte(struct kvm_vcpu *vcpu, u64 *sptep)
1593 {
1594         if (__drop_large_spte(vcpu->kvm, sptep)) {
1595                 struct kvm_mmu_page *sp = page_header(__pa(sptep));
1596
1597                 kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
1598                         KVM_PAGES_PER_HPAGE(sp->role.level));
1599         }
1600 }
1601
1602 /*
1603  * Write-protect on the specified @sptep, @pt_protect indicates whether
1604  * spte write-protection is caused by protecting shadow page table.
1605  *
1606  * Note: write protection is difference between dirty logging and spte
1607  * protection:
1608  * - for dirty logging, the spte can be set to writable at anytime if
1609  *   its dirty bitmap is properly set.
1610  * - for spte protection, the spte can be writable only after unsync-ing
1611  *   shadow page.
1612  *
1613  * Return true if tlb need be flushed.
1614  */
1615 static bool spte_write_protect(u64 *sptep, bool pt_protect)
1616 {
1617         u64 spte = *sptep;
1618
1619         if (!is_writable_pte(spte) &&
1620               !(pt_protect && spte_can_locklessly_be_made_writable(spte)))
1621                 return false;
1622
1623         rmap_printk("rmap_write_protect: spte %p %llx\n", sptep, *sptep);
1624
1625         if (pt_protect)
1626                 spte &= ~SPTE_MMU_WRITEABLE;
1627         spte = spte & ~PT_WRITABLE_MASK;
1628
1629         return mmu_spte_update(sptep, spte);
1630 }
1631
1632 static bool __rmap_write_protect(struct kvm *kvm,
1633                                  struct kvm_rmap_head *rmap_head,
1634                                  bool pt_protect)
1635 {
1636         u64 *sptep;
1637         struct rmap_iterator iter;
1638         bool flush = false;
1639
1640         for_each_rmap_spte(rmap_head, &iter, sptep)
1641                 flush |= spte_write_protect(sptep, pt_protect);
1642
1643         return flush;
1644 }
1645
1646 static bool spte_clear_dirty(u64 *sptep)
1647 {
1648         u64 spte = *sptep;
1649
1650         rmap_printk("rmap_clear_dirty: spte %p %llx\n", sptep, *sptep);
1651
1652         MMU_WARN_ON(!spte_ad_enabled(spte));
1653         spte &= ~shadow_dirty_mask;
1654         return mmu_spte_update(sptep, spte);
1655 }
1656
1657 static bool spte_wrprot_for_clear_dirty(u64 *sptep)
1658 {
1659         bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
1660                                                (unsigned long *)sptep);
1661         if (was_writable && !spte_ad_enabled(*sptep))
1662                 kvm_set_pfn_dirty(spte_to_pfn(*sptep));
1663
1664         return was_writable;
1665 }
1666
1667 /*
1668  * Gets the GFN ready for another round of dirty logging by clearing the
1669  *      - D bit on ad-enabled SPTEs, and
1670  *      - W bit on ad-disabled SPTEs.
1671  * Returns true iff any D or W bits were cleared.
1672  */
1673 static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1674 {
1675         u64 *sptep;
1676         struct rmap_iterator iter;
1677         bool flush = false;
1678
1679         for_each_rmap_spte(rmap_head, &iter, sptep)
1680                 if (spte_ad_need_write_protect(*sptep))
1681                         flush |= spte_wrprot_for_clear_dirty(sptep);
1682                 else
1683                         flush |= spte_clear_dirty(sptep);
1684
1685         return flush;
1686 }
1687
1688 static bool spte_set_dirty(u64 *sptep)
1689 {
1690         u64 spte = *sptep;
1691
1692         rmap_printk("rmap_set_dirty: spte %p %llx\n", sptep, *sptep);
1693
1694         /*
1695          * Similar to the !kvm_x86_ops->slot_disable_log_dirty case,
1696          * do not bother adding back write access to pages marked
1697          * SPTE_AD_WRPROT_ONLY_MASK.
1698          */
1699         spte |= shadow_dirty_mask;
1700
1701         return mmu_spte_update(sptep, spte);
1702 }
1703
1704 static bool __rmap_set_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1705 {
1706         u64 *sptep;
1707         struct rmap_iterator iter;
1708         bool flush = false;
1709
1710         for_each_rmap_spte(rmap_head, &iter, sptep)
1711                 if (spte_ad_enabled(*sptep))
1712                         flush |= spte_set_dirty(sptep);
1713
1714         return flush;
1715 }
1716
1717 /**
1718  * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
1719  * @kvm: kvm instance
1720  * @slot: slot to protect
1721  * @gfn_offset: start of the BITS_PER_LONG pages we care about
1722  * @mask: indicates which pages we should protect
1723  *
1724  * Used when we do not need to care about huge page mappings: e.g. during dirty
1725  * logging we do not have any such mappings.
1726  */
1727 static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1728                                      struct kvm_memory_slot *slot,
1729                                      gfn_t gfn_offset, unsigned long mask)
1730 {
1731         struct kvm_rmap_head *rmap_head;
1732
1733         while (mask) {
1734                 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1735                                           PT_PAGE_TABLE_LEVEL, slot);
1736                 __rmap_write_protect(kvm, rmap_head, false);
1737
1738                 /* clear the first set bit */
1739                 mask &= mask - 1;
1740         }
1741 }
1742
1743 /**
1744  * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
1745  * protect the page if the D-bit isn't supported.
1746  * @kvm: kvm instance
1747  * @slot: slot to clear D-bit
1748  * @gfn_offset: start of the BITS_PER_LONG pages we care about
1749  * @mask: indicates which pages we should clear D-bit
1750  *
1751  * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1752  */
1753 void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1754                                      struct kvm_memory_slot *slot,
1755                                      gfn_t gfn_offset, unsigned long mask)
1756 {
1757         struct kvm_rmap_head *rmap_head;
1758
1759         while (mask) {
1760                 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1761                                           PT_PAGE_TABLE_LEVEL, slot);
1762                 __rmap_clear_dirty(kvm, rmap_head);
1763
1764                 /* clear the first set bit */
1765                 mask &= mask - 1;
1766         }
1767 }
1768 EXPORT_SYMBOL_GPL(kvm_mmu_clear_dirty_pt_masked);
1769
1770 /**
1771  * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1772  * PT level pages.
1773  *
1774  * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1775  * enable dirty logging for them.
1776  *
1777  * Used when we do not need to care about huge page mappings: e.g. during dirty
1778  * logging we do not have any such mappings.
1779  */
1780 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1781                                 struct kvm_memory_slot *slot,
1782                                 gfn_t gfn_offset, unsigned long mask)
1783 {
1784         if (kvm_x86_ops->enable_log_dirty_pt_masked)
1785                 kvm_x86_ops->enable_log_dirty_pt_masked(kvm, slot, gfn_offset,
1786                                 mask);
1787         else
1788                 kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1789 }
1790
1791 /**
1792  * kvm_arch_write_log_dirty - emulate dirty page logging
1793  * @vcpu: Guest mode vcpu
1794  *
1795  * Emulate arch specific page modification logging for the
1796  * nested hypervisor
1797  */
1798 int kvm_arch_write_log_dirty(struct kvm_vcpu *vcpu)
1799 {
1800         if (kvm_x86_ops->write_log_dirty)
1801                 return kvm_x86_ops->write_log_dirty(vcpu);
1802
1803         return 0;
1804 }
1805
1806 bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
1807                                     struct kvm_memory_slot *slot, u64 gfn)
1808 {
1809         struct kvm_rmap_head *rmap_head;
1810         int i;
1811         bool write_protected = false;
1812
1813         for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1814                 rmap_head = __gfn_to_rmap(gfn, i, slot);
1815                 write_protected |= __rmap_write_protect(kvm, rmap_head, true);
1816         }
1817
1818         return write_protected;
1819 }
1820
1821 static bool rmap_write_protect(struct kvm_vcpu *vcpu, u64 gfn)
1822 {
1823         struct kvm_memory_slot *slot;
1824
1825         slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1826         return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn);
1827 }
1828
1829 static bool kvm_zap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1830 {
1831         u64 *sptep;
1832         struct rmap_iterator iter;
1833         bool flush = false;
1834
1835         while ((sptep = rmap_get_first(rmap_head, &iter))) {
1836                 rmap_printk("%s: spte %p %llx.\n", __func__, sptep, *sptep);
1837
1838                 pte_list_remove(rmap_head, sptep);
1839                 flush = true;
1840         }
1841
1842         return flush;
1843 }
1844
1845 static int kvm_unmap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1846                            struct kvm_memory_slot *slot, gfn_t gfn, int level,
1847                            unsigned long data)
1848 {
1849         return kvm_zap_rmapp(kvm, rmap_head);
1850 }
1851
1852 static int kvm_set_pte_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1853                              struct kvm_memory_slot *slot, gfn_t gfn, int level,
1854                              unsigned long data)
1855 {
1856         u64 *sptep;
1857         struct rmap_iterator iter;
1858         int need_flush = 0;
1859         u64 new_spte;
1860         pte_t *ptep = (pte_t *)data;
1861         kvm_pfn_t new_pfn;
1862
1863         WARN_ON(pte_huge(*ptep));
1864         new_pfn = pte_pfn(*ptep);
1865
1866 restart:
1867         for_each_rmap_spte(rmap_head, &iter, sptep) {
1868                 rmap_printk("kvm_set_pte_rmapp: spte %p %llx gfn %llx (%d)\n",
1869                             sptep, *sptep, gfn, level);
1870
1871                 need_flush = 1;
1872
1873                 if (pte_write(*ptep)) {
1874                         pte_list_remove(rmap_head, sptep);
1875                         goto restart;
1876                 } else {
1877                         new_spte = *sptep & ~PT64_BASE_ADDR_MASK;
1878                         new_spte |= (u64)new_pfn << PAGE_SHIFT;
1879
1880                         new_spte &= ~PT_WRITABLE_MASK;
1881                         new_spte &= ~SPTE_HOST_WRITEABLE;
1882
1883                         new_spte = mark_spte_for_access_track(new_spte);
1884
1885                         mmu_spte_clear_track_bits(sptep);
1886                         mmu_spte_set(sptep, new_spte);
1887                 }
1888         }
1889
1890         if (need_flush && kvm_available_flush_tlb_with_range()) {
1891                 kvm_flush_remote_tlbs_with_address(kvm, gfn, 1);
1892                 return 0;
1893         }
1894
1895         return need_flush;
1896 }
1897
1898 struct slot_rmap_walk_iterator {
1899         /* input fields. */
1900         struct kvm_memory_slot *slot;
1901         gfn_t start_gfn;
1902         gfn_t end_gfn;
1903         int start_level;
1904         int end_level;
1905
1906         /* output fields. */
1907         gfn_t gfn;
1908         struct kvm_rmap_head *rmap;
1909         int level;
1910
1911         /* private field. */
1912         struct kvm_rmap_head *end_rmap;
1913 };
1914
1915 static void
1916 rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator, int level)
1917 {
1918         iterator->level = level;
1919         iterator->gfn = iterator->start_gfn;
1920         iterator->rmap = __gfn_to_rmap(iterator->gfn, level, iterator->slot);
1921         iterator->end_rmap = __gfn_to_rmap(iterator->end_gfn, level,
1922                                            iterator->slot);
1923 }
1924
1925 static void
1926 slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1927                     struct kvm_memory_slot *slot, int start_level,
1928                     int end_level, gfn_t start_gfn, gfn_t end_gfn)
1929 {
1930         iterator->slot = slot;
1931         iterator->start_level = start_level;
1932         iterator->end_level = end_level;
1933         iterator->start_gfn = start_gfn;
1934         iterator->end_gfn = end_gfn;
1935
1936         rmap_walk_init_level(iterator, iterator->start_level);
1937 }
1938
1939 static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1940 {
1941         return !!iterator->rmap;
1942 }
1943
1944 static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1945 {
1946         if (++iterator->rmap <= iterator->end_rmap) {
1947                 iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
1948                 return;
1949         }
1950
1951         if (++iterator->level > iterator->end_level) {
1952                 iterator->rmap = NULL;
1953                 return;
1954         }
1955
1956         rmap_walk_init_level(iterator, iterator->level);
1957 }
1958
1959 #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_,    \
1960            _start_gfn, _end_gfn, _iter_)                                \
1961         for (slot_rmap_walk_init(_iter_, _slot_, _start_level_,         \
1962                                  _end_level_, _start_gfn, _end_gfn);    \
1963              slot_rmap_walk_okay(_iter_);                               \
1964              slot_rmap_walk_next(_iter_))
1965
1966 static int kvm_handle_hva_range(struct kvm *kvm,
1967                                 unsigned long start,
1968                                 unsigned long end,
1969                                 unsigned long data,
1970                                 int (*handler)(struct kvm *kvm,
1971                                                struct kvm_rmap_head *rmap_head,
1972                                                struct kvm_memory_slot *slot,
1973                                                gfn_t gfn,
1974                                                int level,
1975                                                unsigned long data))
1976 {
1977         struct kvm_memslots *slots;
1978         struct kvm_memory_slot *memslot;
1979         struct slot_rmap_walk_iterator iterator;
1980         int ret = 0;
1981         int i;
1982
1983         for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1984                 slots = __kvm_memslots(kvm, i);
1985                 kvm_for_each_memslot(memslot, slots) {
1986                         unsigned long hva_start, hva_end;
1987                         gfn_t gfn_start, gfn_end;
1988
1989                         hva_start = max(start, memslot->userspace_addr);
1990                         hva_end = min(end, memslot->userspace_addr +
1991                                       (memslot->npages << PAGE_SHIFT));
1992                         if (hva_start >= hva_end)
1993                                 continue;
1994                         /*
1995                          * {gfn(page) | page intersects with [hva_start, hva_end)} =
1996                          * {gfn_start, gfn_start+1, ..., gfn_end-1}.
1997                          */
1998                         gfn_start = hva_to_gfn_memslot(hva_start, memslot);
1999                         gfn_end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, memslot);
2000
2001                         for_each_slot_rmap_range(memslot, PT_PAGE_TABLE_LEVEL,
2002                                                  PT_MAX_HUGEPAGE_LEVEL,
2003                                                  gfn_start, gfn_end - 1,
2004                                                  &iterator)
2005                                 ret |= handler(kvm, iterator.rmap, memslot,
2006                                                iterator.gfn, iterator.level, data);
2007                 }
2008         }
2009
2010         return ret;
2011 }
2012
2013 static int kvm_handle_hva(struct kvm *kvm, unsigned long hva,
2014                           unsigned long data,
2015                           int (*handler)(struct kvm *kvm,
2016                                          struct kvm_rmap_head *rmap_head,
2017                                          struct kvm_memory_slot *slot,
2018                                          gfn_t gfn, int level,
2019                                          unsigned long data))
2020 {
2021         return kvm_handle_hva_range(kvm, hva, hva + 1, data, handler);
2022 }
2023
2024 int kvm_unmap_hva_range(struct kvm *kvm, unsigned long start, unsigned long end)
2025 {
2026         return kvm_handle_hva_range(kvm, start, end, 0, kvm_unmap_rmapp);
2027 }
2028
2029 int kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte)
2030 {
2031         return kvm_handle_hva(kvm, hva, (unsigned long)&pte, kvm_set_pte_rmapp);
2032 }
2033
2034 static int kvm_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
2035                          struct kvm_memory_slot *slot, gfn_t gfn, int level,
2036                          unsigned long data)
2037 {
2038         u64 *sptep;
2039         struct rmap_iterator uninitialized_var(iter);
2040         int young = 0;
2041
2042         for_each_rmap_spte(rmap_head, &iter, sptep)
2043                 young |= mmu_spte_age(sptep);
2044
2045         trace_kvm_age_page(gfn, level, slot, young);
2046         return young;
2047 }
2048
2049 static int kvm_test_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
2050                               struct kvm_memory_slot *slot, gfn_t gfn,
2051                               int level, unsigned long data)
2052 {
2053         u64 *sptep;
2054         struct rmap_iterator iter;
2055
2056         for_each_rmap_spte(rmap_head, &iter, sptep)
2057                 if (is_accessed_spte(*sptep))
2058                         return 1;
2059         return 0;
2060 }
2061
2062 #define RMAP_RECYCLE_THRESHOLD 1000
2063
2064 static void rmap_recycle(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
2065 {
2066         struct kvm_rmap_head *rmap_head;
2067         struct kvm_mmu_page *sp;
2068
2069         sp = page_header(__pa(spte));
2070
2071         rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
2072
2073         kvm_unmap_rmapp(vcpu->kvm, rmap_head, NULL, gfn, sp->role.level, 0);
2074         kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
2075                         KVM_PAGES_PER_HPAGE(sp->role.level));
2076 }
2077
2078 int kvm_age_hva(struct kvm *kvm, unsigned long start, unsigned long end)
2079 {
2080         return kvm_handle_hva_range(kvm, start, end, 0, kvm_age_rmapp);
2081 }
2082
2083 int kvm_test_age_hva(struct kvm *kvm, unsigned long hva)
2084 {
2085         return kvm_handle_hva(kvm, hva, 0, kvm_test_age_rmapp);
2086 }
2087
2088 #ifdef MMU_DEBUG
2089 static int is_empty_shadow_page(u64 *spt)
2090 {
2091         u64 *pos;
2092         u64 *end;
2093
2094         for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
2095                 if (is_shadow_present_pte(*pos)) {
2096                         printk(KERN_ERR "%s: %p %llx\n", __func__,
2097                                pos, *pos);
2098                         return 0;
2099                 }
2100         return 1;
2101 }
2102 #endif
2103
2104 /*
2105  * This value is the sum of all of the kvm instances's
2106  * kvm->arch.n_used_mmu_pages values.  We need a global,
2107  * aggregate version in order to make the slab shrinker
2108  * faster
2109  */
2110 static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, unsigned long nr)
2111 {
2112         kvm->arch.n_used_mmu_pages += nr;
2113         percpu_counter_add(&kvm_total_used_mmu_pages, nr);
2114 }
2115
2116 static void kvm_mmu_free_page(struct kvm_mmu_page *sp)
2117 {
2118         MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
2119         hlist_del(&sp->hash_link);
2120         list_del(&sp->link);
2121         free_page((unsigned long)sp->spt);
2122         if (!sp->role.direct)
2123                 free_page((unsigned long)sp->gfns);
2124         kmem_cache_free(mmu_page_header_cache, sp);
2125 }
2126
2127 static unsigned kvm_page_table_hashfn(gfn_t gfn)
2128 {
2129         return hash_64(gfn, KVM_MMU_HASH_SHIFT);
2130 }
2131
2132 static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
2133                                     struct kvm_mmu_page *sp, u64 *parent_pte)
2134 {
2135         if (!parent_pte)
2136                 return;
2137
2138         pte_list_add(vcpu, parent_pte, &sp->parent_ptes);
2139 }
2140
2141 static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
2142                                        u64 *parent_pte)
2143 {
2144         __pte_list_remove(parent_pte, &sp->parent_ptes);
2145 }
2146
2147 static void drop_parent_pte(struct kvm_mmu_page *sp,
2148                             u64 *parent_pte)
2149 {
2150         mmu_page_remove_parent_pte(sp, parent_pte);
2151         mmu_spte_clear_no_track(parent_pte);
2152 }
2153
2154 static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, int direct)
2155 {
2156         struct kvm_mmu_page *sp;
2157
2158         sp = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache);
2159         sp->spt = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
2160         if (!direct)
2161                 sp->gfns = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
2162         set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
2163
2164         /*
2165          * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
2166          * depends on valid pages being added to the head of the list.  See
2167          * comments in kvm_zap_obsolete_pages().
2168          */
2169         sp->mmu_valid_gen = vcpu->kvm->arch.mmu_valid_gen;
2170         list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
2171         kvm_mod_used_mmu_pages(vcpu->kvm, +1);
2172         return sp;
2173 }
2174
2175 static void mark_unsync(u64 *spte);
2176 static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
2177 {
2178         u64 *sptep;
2179         struct rmap_iterator iter;
2180
2181         for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
2182                 mark_unsync(sptep);
2183         }
2184 }
2185
2186 static void mark_unsync(u64 *spte)
2187 {
2188         struct kvm_mmu_page *sp;
2189         unsigned int index;
2190
2191         sp = page_header(__pa(spte));
2192         index = spte - sp->spt;
2193         if (__test_and_set_bit(index, sp->unsync_child_bitmap))
2194                 return;
2195         if (sp->unsync_children++)
2196                 return;
2197         kvm_mmu_mark_parents_unsync(sp);
2198 }
2199
2200 static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
2201                                struct kvm_mmu_page *sp)
2202 {
2203         return 0;
2204 }
2205
2206 static void nonpaging_invlpg(struct kvm_vcpu *vcpu, gva_t gva, hpa_t root)
2207 {
2208 }
2209
2210 static void nonpaging_update_pte(struct kvm_vcpu *vcpu,
2211                                  struct kvm_mmu_page *sp, u64 *spte,
2212                                  const void *pte)
2213 {
2214         WARN_ON(1);
2215 }
2216
2217 #define KVM_PAGE_ARRAY_NR 16
2218
2219 struct kvm_mmu_pages {
2220         struct mmu_page_and_offset {
2221                 struct kvm_mmu_page *sp;
2222                 unsigned int idx;
2223         } page[KVM_PAGE_ARRAY_NR];
2224         unsigned int nr;
2225 };
2226
2227 static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
2228                          int idx)
2229 {
2230         int i;
2231
2232         if (sp->unsync)
2233                 for (i=0; i < pvec->nr; i++)
2234                         if (pvec->page[i].sp == sp)
2235                                 return 0;
2236
2237         pvec->page[pvec->nr].sp = sp;
2238         pvec->page[pvec->nr].idx = idx;
2239         pvec->nr++;
2240         return (pvec->nr == KVM_PAGE_ARRAY_NR);
2241 }
2242
2243 static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
2244 {
2245         --sp->unsync_children;
2246         WARN_ON((int)sp->unsync_children < 0);
2247         __clear_bit(idx, sp->unsync_child_bitmap);
2248 }
2249
2250 static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
2251                            struct kvm_mmu_pages *pvec)
2252 {
2253         int i, ret, nr_unsync_leaf = 0;
2254
2255         for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
2256                 struct kvm_mmu_page *child;
2257                 u64 ent = sp->spt[i];
2258
2259                 if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
2260                         clear_unsync_child_bit(sp, i);
2261                         continue;
2262                 }
2263
2264                 child = page_header(ent & PT64_BASE_ADDR_MASK);
2265
2266                 if (child->unsync_children) {
2267                         if (mmu_pages_add(pvec, child, i))
2268                                 return -ENOSPC;
2269
2270                         ret = __mmu_unsync_walk(child, pvec);
2271                         if (!ret) {
2272                                 clear_unsync_child_bit(sp, i);
2273                                 continue;
2274                         } else if (ret > 0) {
2275                                 nr_unsync_leaf += ret;
2276                         } else
2277                                 return ret;
2278                 } else if (child->unsync) {
2279                         nr_unsync_leaf++;
2280                         if (mmu_pages_add(pvec, child, i))
2281                                 return -ENOSPC;
2282                 } else
2283                         clear_unsync_child_bit(sp, i);
2284         }
2285
2286         return nr_unsync_leaf;
2287 }
2288
2289 #define INVALID_INDEX (-1)
2290
2291 static int mmu_unsync_walk(struct kvm_mmu_page *sp,
2292                            struct kvm_mmu_pages *pvec)
2293 {
2294         pvec->nr = 0;
2295         if (!sp->unsync_children)
2296                 return 0;
2297
2298         mmu_pages_add(pvec, sp, INVALID_INDEX);
2299         return __mmu_unsync_walk(sp, pvec);
2300 }
2301
2302 static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2303 {
2304         WARN_ON(!sp->unsync);
2305         trace_kvm_mmu_sync_page(sp);
2306         sp->unsync = 0;
2307         --kvm->stat.mmu_unsync;
2308 }
2309
2310 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2311                                      struct list_head *invalid_list);
2312 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2313                                     struct list_head *invalid_list);
2314
2315
2316 #define for_each_valid_sp(_kvm, _sp, _gfn)                              \
2317         hlist_for_each_entry(_sp,                                       \
2318           &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)], hash_link) \
2319                 if (is_obsolete_sp((_kvm), (_sp))) {                    \
2320                 } else
2321
2322 #define for_each_gfn_indirect_valid_sp(_kvm, _sp, _gfn)                 \
2323         for_each_valid_sp(_kvm, _sp, _gfn)                              \
2324                 if ((_sp)->gfn != (_gfn) || (_sp)->role.direct) {} else
2325
2326 static inline bool is_ept_sp(struct kvm_mmu_page *sp)
2327 {
2328         return sp->role.cr0_wp && sp->role.smap_andnot_wp;
2329 }
2330
2331 /* @sp->gfn should be write-protected at the call site */
2332 static bool __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2333                             struct list_head *invalid_list)
2334 {
2335         if ((!is_ept_sp(sp) && sp->role.gpte_is_8_bytes != !!is_pae(vcpu)) ||
2336             vcpu->arch.mmu->sync_page(vcpu, sp) == 0) {
2337                 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
2338                 return false;
2339         }
2340
2341         return true;
2342 }
2343
2344 static bool kvm_mmu_remote_flush_or_zap(struct kvm *kvm,
2345                                         struct list_head *invalid_list,
2346                                         bool remote_flush)
2347 {
2348         if (!remote_flush && list_empty(invalid_list))
2349                 return false;
2350
2351         if (!list_empty(invalid_list))
2352                 kvm_mmu_commit_zap_page(kvm, invalid_list);
2353         else
2354                 kvm_flush_remote_tlbs(kvm);
2355         return true;
2356 }
2357
2358 static void kvm_mmu_flush_or_zap(struct kvm_vcpu *vcpu,
2359                                  struct list_head *invalid_list,
2360                                  bool remote_flush, bool local_flush)
2361 {
2362         if (kvm_mmu_remote_flush_or_zap(vcpu->kvm, invalid_list, remote_flush))
2363                 return;
2364
2365         if (local_flush)
2366                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2367 }
2368
2369 #ifdef CONFIG_KVM_MMU_AUDIT
2370 #include "mmu_audit.c"
2371 #else
2372 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, int point) { }
2373 static void mmu_audit_disable(void) { }
2374 #endif
2375
2376 static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
2377 {
2378         return sp->role.invalid ||
2379                unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
2380 }
2381
2382 static bool kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2383                          struct list_head *invalid_list)
2384 {
2385         kvm_unlink_unsync_page(vcpu->kvm, sp);
2386         return __kvm_sync_page(vcpu, sp, invalid_list);
2387 }
2388
2389 /* @gfn should be write-protected at the call site */
2390 static bool kvm_sync_pages(struct kvm_vcpu *vcpu, gfn_t gfn,
2391                            struct list_head *invalid_list)
2392 {
2393         struct kvm_mmu_page *s;
2394         bool ret = false;
2395
2396         for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
2397                 if (!s->unsync)
2398                         continue;
2399
2400                 WARN_ON(s->role.level != PT_PAGE_TABLE_LEVEL);
2401                 ret |= kvm_sync_page(vcpu, s, invalid_list);
2402         }
2403
2404         return ret;
2405 }
2406
2407 struct mmu_page_path {
2408         struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
2409         unsigned int idx[PT64_ROOT_MAX_LEVEL];
2410 };
2411
2412 #define for_each_sp(pvec, sp, parents, i)                       \
2413                 for (i = mmu_pages_first(&pvec, &parents);      \
2414                         i < pvec.nr && ({ sp = pvec.page[i].sp; 1;});   \
2415                         i = mmu_pages_next(&pvec, &parents, i))
2416
2417 static int mmu_pages_next(struct kvm_mmu_pages *pvec,
2418                           struct mmu_page_path *parents,
2419                           int i)
2420 {
2421         int n;
2422
2423         for (n = i+1; n < pvec->nr; n++) {
2424                 struct kvm_mmu_page *sp = pvec->page[n].sp;
2425                 unsigned idx = pvec->page[n].idx;
2426                 int level = sp->role.level;
2427
2428                 parents->idx[level-1] = idx;
2429                 if (level == PT_PAGE_TABLE_LEVEL)
2430                         break;
2431
2432                 parents->parent[level-2] = sp;
2433         }
2434
2435         return n;
2436 }
2437
2438 static int mmu_pages_first(struct kvm_mmu_pages *pvec,
2439                            struct mmu_page_path *parents)
2440 {
2441         struct kvm_mmu_page *sp;
2442         int level;
2443
2444         if (pvec->nr == 0)
2445                 return 0;
2446
2447         WARN_ON(pvec->page[0].idx != INVALID_INDEX);
2448
2449         sp = pvec->page[0].sp;
2450         level = sp->role.level;
2451         WARN_ON(level == PT_PAGE_TABLE_LEVEL);
2452
2453         parents->parent[level-2] = sp;
2454
2455         /* Also set up a sentinel.  Further entries in pvec are all
2456          * children of sp, so this element is never overwritten.
2457          */
2458         parents->parent[level-1] = NULL;
2459         return mmu_pages_next(pvec, parents, 0);
2460 }
2461
2462 static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2463 {
2464         struct kvm_mmu_page *sp;
2465         unsigned int level = 0;
2466
2467         do {
2468                 unsigned int idx = parents->idx[level];
2469                 sp = parents->parent[level];
2470                 if (!sp)
2471                         return;
2472
2473                 WARN_ON(idx == INVALID_INDEX);
2474                 clear_unsync_child_bit(sp, idx);
2475                 level++;
2476         } while (!sp->unsync_children);
2477 }
2478
2479 static void mmu_sync_children(struct kvm_vcpu *vcpu,
2480                               struct kvm_mmu_page *parent)
2481 {
2482         int i;
2483         struct kvm_mmu_page *sp;
2484         struct mmu_page_path parents;
2485         struct kvm_mmu_pages pages;
2486         LIST_HEAD(invalid_list);
2487         bool flush = false;
2488
2489         while (mmu_unsync_walk(parent, &pages)) {
2490                 bool protected = false;
2491
2492                 for_each_sp(pages, sp, parents, i)
2493                         protected |= rmap_write_protect(vcpu, sp->gfn);
2494
2495                 if (protected) {
2496                         kvm_flush_remote_tlbs(vcpu->kvm);
2497                         flush = false;
2498                 }
2499
2500                 for_each_sp(pages, sp, parents, i) {
2501                         flush |= kvm_sync_page(vcpu, sp, &invalid_list);
2502                         mmu_pages_clear_parents(&parents);
2503                 }
2504                 if (need_resched() || spin_needbreak(&vcpu->kvm->mmu_lock)) {
2505                         kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2506                         cond_resched_lock(&vcpu->kvm->mmu_lock);
2507                         flush = false;
2508                 }
2509         }
2510
2511         kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2512 }
2513
2514 static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2515 {
2516         atomic_set(&sp->write_flooding_count,  0);
2517 }
2518
2519 static void clear_sp_write_flooding_count(u64 *spte)
2520 {
2521         struct kvm_mmu_page *sp =  page_header(__pa(spte));
2522
2523         __clear_sp_write_flooding_count(sp);
2524 }
2525
2526 static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
2527                                              gfn_t gfn,
2528                                              gva_t gaddr,
2529                                              unsigned level,
2530                                              int direct,
2531                                              unsigned access)
2532 {
2533         union kvm_mmu_page_role role;
2534         unsigned quadrant;
2535         struct kvm_mmu_page *sp;
2536         bool need_sync = false;
2537         bool flush = false;
2538         int collisions = 0;
2539         LIST_HEAD(invalid_list);
2540
2541         role = vcpu->arch.mmu->mmu_role.base;
2542         role.level = level;
2543         role.direct = direct;
2544         if (role.direct)
2545                 role.gpte_is_8_bytes = true;
2546         role.access = access;
2547         if (!vcpu->arch.mmu->direct_map
2548             && vcpu->arch.mmu->root_level <= PT32_ROOT_LEVEL) {
2549                 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
2550                 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
2551                 role.quadrant = quadrant;
2552         }
2553         for_each_valid_sp(vcpu->kvm, sp, gfn) {
2554                 if (sp->gfn != gfn) {
2555                         collisions++;
2556                         continue;
2557                 }
2558
2559                 if (!need_sync && sp->unsync)
2560                         need_sync = true;
2561
2562                 if (sp->role.word != role.word)
2563                         continue;
2564
2565                 if (sp->unsync) {
2566                         /* The page is good, but __kvm_sync_page might still end
2567                          * up zapping it.  If so, break in order to rebuild it.
2568                          */
2569                         if (!__kvm_sync_page(vcpu, sp, &invalid_list))
2570                                 break;
2571
2572                         WARN_ON(!list_empty(&invalid_list));
2573                         kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2574                 }
2575
2576                 if (sp->unsync_children)
2577                         kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
2578
2579                 __clear_sp_write_flooding_count(sp);
2580                 trace_kvm_mmu_get_page(sp, false);
2581                 goto out;
2582         }
2583
2584         ++vcpu->kvm->stat.mmu_cache_miss;
2585
2586         sp = kvm_mmu_alloc_page(vcpu, direct);
2587
2588         sp->gfn = gfn;
2589         sp->role = role;
2590         hlist_add_head(&sp->hash_link,
2591                 &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)]);
2592         if (!direct) {
2593                 /*
2594                  * we should do write protection before syncing pages
2595                  * otherwise the content of the synced shadow page may
2596                  * be inconsistent with guest page table.
2597                  */
2598                 account_shadowed(vcpu->kvm, sp);
2599                 if (level == PT_PAGE_TABLE_LEVEL &&
2600                       rmap_write_protect(vcpu, gfn))
2601                         kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn, 1);
2602
2603                 if (level > PT_PAGE_TABLE_LEVEL && need_sync)
2604                         flush |= kvm_sync_pages(vcpu, gfn, &invalid_list);
2605         }
2606         clear_page(sp->spt);
2607         trace_kvm_mmu_get_page(sp, true);
2608
2609         kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2610 out:
2611         if (collisions > vcpu->kvm->stat.max_mmu_page_hash_collisions)
2612                 vcpu->kvm->stat.max_mmu_page_hash_collisions = collisions;
2613         return sp;
2614 }
2615
2616 static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2617                                         struct kvm_vcpu *vcpu, hpa_t root,
2618                                         u64 addr)
2619 {
2620         iterator->addr = addr;
2621         iterator->shadow_addr = root;
2622         iterator->level = vcpu->arch.mmu->shadow_root_level;
2623
2624         if (iterator->level == PT64_ROOT_4LEVEL &&
2625             vcpu->arch.mmu->root_level < PT64_ROOT_4LEVEL &&
2626             !vcpu->arch.mmu->direct_map)
2627                 --iterator->level;
2628
2629         if (iterator->level == PT32E_ROOT_LEVEL) {
2630                 /*
2631                  * prev_root is currently only used for 64-bit hosts. So only
2632                  * the active root_hpa is valid here.
2633                  */
2634                 BUG_ON(root != vcpu->arch.mmu->root_hpa);
2635
2636                 iterator->shadow_addr
2637                         = vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
2638                 iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
2639                 --iterator->level;
2640                 if (!iterator->shadow_addr)
2641                         iterator->level = 0;
2642         }
2643 }
2644
2645 static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2646                              struct kvm_vcpu *vcpu, u64 addr)
2647 {
2648         shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root_hpa,
2649                                     addr);
2650 }
2651
2652 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2653 {
2654         if (iterator->level < PT_PAGE_TABLE_LEVEL)
2655                 return false;
2656
2657         iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
2658         iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2659         return true;
2660 }
2661
2662 static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2663                                u64 spte)
2664 {
2665         if (is_last_spte(spte, iterator->level)) {
2666                 iterator->level = 0;
2667                 return;
2668         }
2669
2670         iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK;
2671         --iterator->level;
2672 }
2673
2674 static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2675 {
2676         __shadow_walk_next(iterator, *iterator->sptep);
2677 }
2678
2679 static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2680                              struct kvm_mmu_page *sp)
2681 {
2682         u64 spte;
2683
2684         BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2685
2686         spte = __pa(sp->spt) | shadow_present_mask | PT_WRITABLE_MASK |
2687                shadow_user_mask | shadow_x_mask | shadow_me_mask;
2688
2689         if (sp_ad_disabled(sp))
2690                 spte |= SPTE_AD_DISABLED_MASK;
2691         else
2692                 spte |= shadow_accessed_mask;
2693
2694         mmu_spte_set(sptep, spte);
2695
2696         mmu_page_add_parent_pte(vcpu, sp, sptep);
2697
2698         if (sp->unsync_children || sp->unsync)
2699                 mark_unsync(sptep);
2700 }
2701
2702 static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2703                                    unsigned direct_access)
2704 {
2705         if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2706                 struct kvm_mmu_page *child;
2707
2708                 /*
2709                  * For the direct sp, if the guest pte's dirty bit
2710                  * changed form clean to dirty, it will corrupt the
2711                  * sp's access: allow writable in the read-only sp,
2712                  * so we should update the spte at this point to get
2713                  * a new sp with the correct access.
2714                  */
2715                 child = page_header(*sptep & PT64_BASE_ADDR_MASK);
2716                 if (child->role.access == direct_access)
2717                         return;
2718
2719                 drop_parent_pte(child, sptep);
2720                 kvm_flush_remote_tlbs_with_address(vcpu->kvm, child->gfn, 1);
2721         }
2722 }
2723
2724 static bool mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
2725                              u64 *spte)
2726 {
2727         u64 pte;
2728         struct kvm_mmu_page *child;
2729
2730         pte = *spte;
2731         if (is_shadow_present_pte(pte)) {
2732                 if (is_last_spte(pte, sp->role.level)) {
2733                         drop_spte(kvm, spte);
2734                         if (is_large_pte(pte))
2735                                 --kvm->stat.lpages;
2736                 } else {
2737                         child = page_header(pte & PT64_BASE_ADDR_MASK);
2738                         drop_parent_pte(child, spte);
2739                 }
2740                 return true;
2741         }
2742
2743         if (is_mmio_spte(pte))
2744                 mmu_spte_clear_no_track(spte);
2745
2746         return false;
2747 }
2748
2749 static void kvm_mmu_page_unlink_children(struct kvm *kvm,
2750                                          struct kvm_mmu_page *sp)
2751 {
2752         unsigned i;
2753
2754         for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
2755                 mmu_page_zap_pte(kvm, sp, sp->spt + i);
2756 }
2757
2758 static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
2759 {
2760         u64 *sptep;
2761         struct rmap_iterator iter;
2762
2763         while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2764                 drop_parent_pte(sp, sptep);
2765 }
2766
2767 static int mmu_zap_unsync_children(struct kvm *kvm,
2768                                    struct kvm_mmu_page *parent,
2769                                    struct list_head *invalid_list)
2770 {
2771         int i, zapped = 0;
2772         struct mmu_page_path parents;
2773         struct kvm_mmu_pages pages;
2774
2775         if (parent->role.level == PT_PAGE_TABLE_LEVEL)
2776                 return 0;
2777
2778         while (mmu_unsync_walk(parent, &pages)) {
2779                 struct kvm_mmu_page *sp;
2780
2781                 for_each_sp(pages, sp, parents, i) {
2782                         kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2783                         mmu_pages_clear_parents(&parents);
2784                         zapped++;
2785                 }
2786         }
2787
2788         return zapped;
2789 }
2790
2791 static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
2792                                        struct kvm_mmu_page *sp,
2793                                        struct list_head *invalid_list,
2794                                        int *nr_zapped)
2795 {
2796         bool list_unstable;
2797
2798         trace_kvm_mmu_prepare_zap_page(sp);
2799         ++kvm->stat.mmu_shadow_zapped;
2800         *nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
2801         kvm_mmu_page_unlink_children(kvm, sp);
2802         kvm_mmu_unlink_parents(kvm, sp);
2803
2804         /* Zapping children means active_mmu_pages has become unstable. */
2805         list_unstable = *nr_zapped;
2806
2807         if (!sp->role.invalid && !sp->role.direct)
2808                 unaccount_shadowed(kvm, sp);
2809
2810         if (sp->unsync)
2811                 kvm_unlink_unsync_page(kvm, sp);
2812         if (!sp->root_count) {
2813                 /* Count self */
2814                 (*nr_zapped)++;
2815                 list_move(&sp->link, invalid_list);
2816                 kvm_mod_used_mmu_pages(kvm, -1);
2817         } else {
2818                 list_move(&sp->link, &kvm->arch.active_mmu_pages);
2819
2820                 /*
2821                  * Obsolete pages cannot be used on any vCPUs, see the comment
2822                  * in kvm_mmu_zap_all_fast().  Note, is_obsolete_sp() also
2823                  * treats invalid shadow pages as being obsolete.
2824                  */
2825                 if (!is_obsolete_sp(kvm, sp))
2826                         kvm_reload_remote_mmus(kvm);
2827         }
2828
2829         if (sp->lpage_disallowed)
2830                 unaccount_huge_nx_page(kvm, sp);
2831
2832         sp->role.invalid = 1;
2833         return list_unstable;
2834 }
2835
2836 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2837                                      struct list_head *invalid_list)
2838 {
2839         int nr_zapped;
2840
2841         __kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
2842         return nr_zapped;
2843 }
2844
2845 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2846                                     struct list_head *invalid_list)
2847 {
2848         struct kvm_mmu_page *sp, *nsp;
2849
2850         if (list_empty(invalid_list))
2851                 return;
2852
2853         /*
2854          * We need to make sure everyone sees our modifications to
2855          * the page tables and see changes to vcpu->mode here. The barrier
2856          * in the kvm_flush_remote_tlbs() achieves this. This pairs
2857          * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2858          *
2859          * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2860          * guest mode and/or lockless shadow page table walks.
2861          */
2862         kvm_flush_remote_tlbs(kvm);
2863
2864         list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2865                 WARN_ON(!sp->role.invalid || sp->root_count);
2866                 kvm_mmu_free_page(sp);
2867         }
2868 }
2869
2870 static bool prepare_zap_oldest_mmu_page(struct kvm *kvm,
2871                                         struct list_head *invalid_list)
2872 {
2873         struct kvm_mmu_page *sp;
2874
2875         if (list_empty(&kvm->arch.active_mmu_pages))
2876                 return false;
2877
2878         sp = list_last_entry(&kvm->arch.active_mmu_pages,
2879                              struct kvm_mmu_page, link);
2880         return kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2881 }
2882
2883 /*
2884  * Changing the number of mmu pages allocated to the vm
2885  * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2886  */
2887 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
2888 {
2889         LIST_HEAD(invalid_list);
2890
2891         spin_lock(&kvm->mmu_lock);
2892
2893         if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
2894                 /* Need to free some mmu pages to achieve the goal. */
2895                 while (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages)
2896                         if (!prepare_zap_oldest_mmu_page(kvm, &invalid_list))
2897                                 break;
2898
2899                 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2900                 goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2901         }
2902
2903         kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2904
2905         spin_unlock(&kvm->mmu_lock);
2906 }
2907
2908 int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2909 {
2910         struct kvm_mmu_page *sp;
2911         LIST_HEAD(invalid_list);
2912         int r;
2913
2914         pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
2915         r = 0;
2916         spin_lock(&kvm->mmu_lock);
2917         for_each_gfn_indirect_valid_sp(kvm, sp, gfn) {
2918                 pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
2919                          sp->role.word);
2920                 r = 1;
2921                 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2922         }
2923         kvm_mmu_commit_zap_page(kvm, &invalid_list);
2924         spin_unlock(&kvm->mmu_lock);
2925
2926         return r;
2927 }
2928 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page);
2929
2930 static void kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
2931 {
2932         trace_kvm_mmu_unsync_page(sp);
2933         ++vcpu->kvm->stat.mmu_unsync;
2934         sp->unsync = 1;
2935
2936         kvm_mmu_mark_parents_unsync(sp);
2937 }
2938
2939 static bool mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
2940                                    bool can_unsync)
2941 {
2942         struct kvm_mmu_page *sp;
2943
2944         if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
2945                 return true;
2946
2947         for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
2948                 if (!can_unsync)
2949                         return true;
2950
2951                 if (sp->unsync)
2952                         continue;
2953
2954                 WARN_ON(sp->role.level != PT_PAGE_TABLE_LEVEL);
2955                 kvm_unsync_page(vcpu, sp);
2956         }
2957
2958         /*
2959          * We need to ensure that the marking of unsync pages is visible
2960          * before the SPTE is updated to allow writes because
2961          * kvm_mmu_sync_roots() checks the unsync flags without holding
2962          * the MMU lock and so can race with this. If the SPTE was updated
2963          * before the page had been marked as unsync-ed, something like the
2964          * following could happen:
2965          *
2966          * CPU 1                    CPU 2
2967          * ---------------------------------------------------------------------
2968          * 1.2 Host updates SPTE
2969          *     to be writable
2970          *                      2.1 Guest writes a GPTE for GVA X.
2971          *                          (GPTE being in the guest page table shadowed
2972          *                           by the SP from CPU 1.)
2973          *                          This reads SPTE during the page table walk.
2974          *                          Since SPTE.W is read as 1, there is no
2975          *                          fault.
2976          *
2977          *                      2.2 Guest issues TLB flush.
2978          *                          That causes a VM Exit.
2979          *
2980          *                      2.3 kvm_mmu_sync_pages() reads sp->unsync.
2981          *                          Since it is false, so it just returns.
2982          *
2983          *                      2.4 Guest accesses GVA X.
2984          *                          Since the mapping in the SP was not updated,
2985          *                          so the old mapping for GVA X incorrectly
2986          *                          gets used.
2987          * 1.1 Host marks SP
2988          *     as unsync
2989          *     (sp->unsync = true)
2990          *
2991          * The write barrier below ensures that 1.1 happens before 1.2 and thus
2992          * the situation in 2.4 does not arise. The implicit barrier in 2.2
2993          * pairs with this write barrier.
2994          */
2995         smp_wmb();
2996
2997         return false;
2998 }
2999
3000 static bool kvm_is_mmio_pfn(kvm_pfn_t pfn)
3001 {
3002         if (pfn_valid(pfn))
3003                 return !is_zero_pfn(pfn) && PageReserved(pfn_to_page(pfn)) &&
3004                         /*
3005                          * Some reserved pages, such as those from NVDIMM
3006                          * DAX devices, are not for MMIO, and can be mapped
3007                          * with cached memory type for better performance.
3008                          * However, the above check misconceives those pages
3009                          * as MMIO, and results in KVM mapping them with UC
3010                          * memory type, which would hurt the performance.
3011                          * Therefore, we check the host memory type in addition
3012                          * and only treat UC/UC-/WC pages as MMIO.
3013                          */
3014                         (!pat_enabled() || pat_pfn_immune_to_uc_mtrr(pfn));
3015
3016         return !e820__mapped_raw_any(pfn_to_hpa(pfn),
3017                                      pfn_to_hpa(pfn + 1) - 1,
3018                                      E820_TYPE_RAM);
3019 }
3020
3021 /* Bits which may be returned by set_spte() */
3022 #define SET_SPTE_WRITE_PROTECTED_PT     BIT(0)
3023 #define SET_SPTE_NEED_REMOTE_TLB_FLUSH  BIT(1)
3024
3025 static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
3026                     unsigned pte_access, int level,
3027                     gfn_t gfn, kvm_pfn_t pfn, bool speculative,
3028                     bool can_unsync, bool host_writable)
3029 {
3030         u64 spte = 0;
3031         int ret = 0;
3032         struct kvm_mmu_page *sp;
3033
3034         if (set_mmio_spte(vcpu, sptep, gfn, pfn, pte_access))
3035                 return 0;
3036
3037         sp = page_header(__pa(sptep));
3038         if (sp_ad_disabled(sp))
3039                 spte |= SPTE_AD_DISABLED_MASK;
3040         else if (kvm_vcpu_ad_need_write_protect(vcpu))
3041                 spte |= SPTE_AD_WRPROT_ONLY_MASK;
3042
3043         /*
3044          * For the EPT case, shadow_present_mask is 0 if hardware
3045          * supports exec-only page table entries.  In that case,
3046          * ACC_USER_MASK and shadow_user_mask are used to represent
3047          * read access.  See FNAME(gpte_access) in paging_tmpl.h.
3048          */
3049         spte |= shadow_present_mask;
3050         if (!speculative)
3051                 spte |= spte_shadow_accessed_mask(spte);
3052
3053         if (level > PT_PAGE_TABLE_LEVEL && (pte_access & ACC_EXEC_MASK) &&
3054             is_nx_huge_page_enabled()) {
3055                 pte_access &= ~ACC_EXEC_MASK;
3056         }
3057
3058         if (pte_access & ACC_EXEC_MASK)
3059                 spte |= shadow_x_mask;
3060         else
3061                 spte |= shadow_nx_mask;
3062
3063         if (pte_access & ACC_USER_MASK)
3064                 spte |= shadow_user_mask;
3065
3066         if (level > PT_PAGE_TABLE_LEVEL)
3067                 spte |= PT_PAGE_SIZE_MASK;
3068         if (tdp_enabled)
3069                 spte |= kvm_x86_ops->get_mt_mask(vcpu, gfn,
3070                         kvm_is_mmio_pfn(pfn));
3071
3072         if (host_writable)
3073                 spte |= SPTE_HOST_WRITEABLE;
3074         else
3075                 pte_access &= ~ACC_WRITE_MASK;
3076
3077         if (!kvm_is_mmio_pfn(pfn))
3078                 spte |= shadow_me_mask;
3079
3080         spte |= (u64)pfn << PAGE_SHIFT;
3081
3082         if (pte_access & ACC_WRITE_MASK) {
3083
3084                 /*
3085                  * Other vcpu creates new sp in the window between
3086                  * mapping_level() and acquiring mmu-lock. We can
3087                  * allow guest to retry the access, the mapping can
3088                  * be fixed if guest refault.
3089                  */
3090                 if (level > PT_PAGE_TABLE_LEVEL &&
3091                     mmu_gfn_lpage_is_disallowed(vcpu, gfn, level))
3092                         goto done;
3093
3094                 spte |= PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE;
3095
3096                 /*
3097                  * Optimization: for pte sync, if spte was writable the hash
3098                  * lookup is unnecessary (and expensive). Write protection
3099                  * is responsibility of mmu_get_page / kvm_sync_page.
3100                  * Same reasoning can be applied to dirty page accounting.
3101                  */
3102                 if (!can_unsync && is_writable_pte(*sptep))
3103                         goto set_pte;
3104
3105                 if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
3106                         pgprintk("%s: found shadow page for %llx, marking ro\n",
3107                                  __func__, gfn);
3108                         ret |= SET_SPTE_WRITE_PROTECTED_PT;
3109                         pte_access &= ~ACC_WRITE_MASK;
3110                         spte &= ~(PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE);
3111                 }
3112         }
3113
3114         if (pte_access & ACC_WRITE_MASK) {
3115                 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3116                 spte |= spte_shadow_dirty_mask(spte);
3117         }
3118
3119         if (speculative)
3120                 spte = mark_spte_for_access_track(spte);
3121
3122 set_pte:
3123         if (mmu_spte_update(sptep, spte))
3124                 ret |= SET_SPTE_NEED_REMOTE_TLB_FLUSH;
3125 done:
3126         return ret;
3127 }
3128
3129 static int mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep, unsigned pte_access,
3130                         int write_fault, int level, gfn_t gfn, kvm_pfn_t pfn,
3131                         bool speculative, bool host_writable)
3132 {
3133         int was_rmapped = 0;
3134         int rmap_count;
3135         int set_spte_ret;
3136         int ret = RET_PF_RETRY;
3137         bool flush = false;
3138
3139         pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
3140                  *sptep, write_fault, gfn);
3141
3142         if (is_shadow_present_pte(*sptep)) {
3143                 /*
3144                  * If we overwrite a PTE page pointer with a 2MB PMD, unlink
3145                  * the parent of the now unreachable PTE.
3146                  */
3147                 if (level > PT_PAGE_TABLE_LEVEL &&
3148                     !is_large_pte(*sptep)) {
3149                         struct kvm_mmu_page *child;
3150                         u64 pte = *sptep;
3151
3152                         child = page_header(pte & PT64_BASE_ADDR_MASK);
3153                         drop_parent_pte(child, sptep);
3154                         flush = true;
3155                 } else if (pfn != spte_to_pfn(*sptep)) {
3156                         pgprintk("hfn old %llx new %llx\n",
3157                                  spte_to_pfn(*sptep), pfn);
3158                         drop_spte(vcpu->kvm, sptep);
3159                         flush = true;
3160                 } else
3161                         was_rmapped = 1;
3162         }
3163
3164         set_spte_ret = set_spte(vcpu, sptep, pte_access, level, gfn, pfn,
3165                                 speculative, true, host_writable);
3166         if (set_spte_ret & SET_SPTE_WRITE_PROTECTED_PT) {
3167                 if (write_fault)
3168                         ret = RET_PF_EMULATE;
3169                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
3170         }
3171
3172         if (set_spte_ret & SET_SPTE_NEED_REMOTE_TLB_FLUSH || flush)
3173                 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn,
3174                                 KVM_PAGES_PER_HPAGE(level));
3175
3176         if (unlikely(is_mmio_spte(*sptep)))
3177                 ret = RET_PF_EMULATE;
3178
3179         pgprintk("%s: setting spte %llx\n", __func__, *sptep);
3180         trace_kvm_mmu_set_spte(level, gfn, sptep);
3181         if (!was_rmapped && is_large_pte(*sptep))
3182                 ++vcpu->kvm->stat.lpages;
3183
3184         if (is_shadow_present_pte(*sptep)) {
3185                 if (!was_rmapped) {
3186                         rmap_count = rmap_add(vcpu, sptep, gfn);
3187                         if (rmap_count > RMAP_RECYCLE_THRESHOLD)
3188                                 rmap_recycle(vcpu, sptep, gfn);
3189                 }
3190         }
3191
3192         return ret;
3193 }
3194
3195 static kvm_pfn_t pte_prefetch_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn,
3196                                      bool no_dirty_log)
3197 {
3198         struct kvm_memory_slot *slot;
3199
3200         slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, no_dirty_log);
3201         if (!slot)
3202                 return KVM_PFN_ERR_FAULT;
3203
3204         return gfn_to_pfn_memslot_atomic(slot, gfn);
3205 }
3206
3207 static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
3208                                     struct kvm_mmu_page *sp,
3209                                     u64 *start, u64 *end)
3210 {
3211         struct page *pages[PTE_PREFETCH_NUM];
3212         struct kvm_memory_slot *slot;
3213         unsigned access = sp->role.access;
3214         int i, ret;
3215         gfn_t gfn;
3216
3217         gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
3218         slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
3219         if (!slot)
3220                 return -1;
3221
3222         ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
3223         if (ret <= 0)
3224                 return -1;
3225
3226         for (i = 0; i < ret; i++, gfn++, start++) {
3227                 mmu_set_spte(vcpu, start, access, 0, sp->role.level, gfn,
3228                              page_to_pfn(pages[i]), true, true);
3229                 put_page(pages[i]);
3230         }
3231
3232         return 0;
3233 }
3234
3235 static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
3236                                   struct kvm_mmu_page *sp, u64 *sptep)
3237 {
3238         u64 *spte, *start = NULL;
3239         int i;
3240
3241         WARN_ON(!sp->role.direct);
3242
3243         i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
3244         spte = sp->spt + i;
3245
3246         for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
3247                 if (is_shadow_present_pte(*spte) || spte == sptep) {
3248                         if (!start)
3249                                 continue;
3250                         if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
3251                                 break;
3252                         start = NULL;
3253                 } else if (!start)
3254                         start = spte;
3255         }
3256 }
3257
3258 static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
3259 {
3260         struct kvm_mmu_page *sp;
3261
3262         sp = page_header(__pa(sptep));
3263
3264         /*
3265          * Without accessed bits, there's no way to distinguish between
3266          * actually accessed translations and prefetched, so disable pte
3267          * prefetch if accessed bits aren't available.
3268          */
3269         if (sp_ad_disabled(sp))
3270                 return;
3271
3272         if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3273                 return;
3274
3275         __direct_pte_prefetch(vcpu, sp, sptep);
3276 }
3277
3278 static void disallowed_hugepage_adjust(struct kvm_shadow_walk_iterator it,
3279                                        gfn_t gfn, kvm_pfn_t *pfnp, int *levelp)
3280 {
3281         int level = *levelp;
3282         u64 spte = *it.sptep;
3283
3284         if (it.level == level && level > PT_PAGE_TABLE_LEVEL &&
3285             is_nx_huge_page_enabled() &&
3286             is_shadow_present_pte(spte) &&
3287             !is_large_pte(spte)) {
3288                 /*
3289                  * A small SPTE exists for this pfn, but FNAME(fetch)
3290                  * and __direct_map would like to create a large PTE
3291                  * instead: just force them to go down another level,
3292                  * patching back for them into pfn the next 9 bits of
3293                  * the address.
3294                  */
3295                 u64 page_mask = KVM_PAGES_PER_HPAGE(level) - KVM_PAGES_PER_HPAGE(level - 1);
3296                 *pfnp |= gfn & page_mask;
3297                 (*levelp)--;
3298         }
3299 }
3300
3301 static int __direct_map(struct kvm_vcpu *vcpu, gpa_t gpa, int write,
3302                         int map_writable, int level, kvm_pfn_t pfn,
3303                         bool prefault, bool lpage_disallowed)
3304 {
3305         struct kvm_shadow_walk_iterator it;
3306         struct kvm_mmu_page *sp;
3307         int ret;
3308         gfn_t gfn = gpa >> PAGE_SHIFT;
3309         gfn_t base_gfn = gfn;
3310
3311         if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3312                 return RET_PF_RETRY;
3313
3314         trace_kvm_mmu_spte_requested(gpa, level, pfn);
3315         for_each_shadow_entry(vcpu, gpa, it) {
3316                 /*
3317                  * We cannot overwrite existing page tables with an NX
3318                  * large page, as the leaf could be executable.
3319                  */
3320                 disallowed_hugepage_adjust(it, gfn, &pfn, &level);
3321
3322                 base_gfn = gfn & ~(KVM_PAGES_PER_HPAGE(it.level) - 1);
3323                 if (it.level == level)
3324                         break;
3325
3326                 drop_large_spte(vcpu, it.sptep);
3327                 if (!is_shadow_present_pte(*it.sptep)) {
3328                         sp = kvm_mmu_get_page(vcpu, base_gfn, it.addr,
3329                                               it.level - 1, true, ACC_ALL);
3330
3331                         link_shadow_page(vcpu, it.sptep, sp);
3332                         if (lpage_disallowed)
3333                                 account_huge_nx_page(vcpu->kvm, sp);
3334                 }
3335         }
3336
3337         ret = mmu_set_spte(vcpu, it.sptep, ACC_ALL,
3338                            write, level, base_gfn, pfn, prefault,
3339                            map_writable);
3340         direct_pte_prefetch(vcpu, it.sptep);
3341         ++vcpu->stat.pf_fixed;
3342         return ret;
3343 }
3344
3345 static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
3346 {
3347         send_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, PAGE_SHIFT, tsk);
3348 }
3349
3350 static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)
3351 {
3352         /*
3353          * Do not cache the mmio info caused by writing the readonly gfn
3354          * into the spte otherwise read access on readonly gfn also can
3355          * caused mmio page fault and treat it as mmio access.
3356          */
3357         if (pfn == KVM_PFN_ERR_RO_FAULT)
3358                 return RET_PF_EMULATE;
3359
3360         if (pfn == KVM_PFN_ERR_HWPOISON) {
3361                 kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu, gfn), current);
3362                 return RET_PF_RETRY;
3363         }
3364
3365         return -EFAULT;
3366 }
3367
3368 static void transparent_hugepage_adjust(struct kvm_vcpu *vcpu,
3369                                         gfn_t gfn, kvm_pfn_t *pfnp,
3370                                         int *levelp)
3371 {
3372         kvm_pfn_t pfn = *pfnp;
3373         int level = *levelp;
3374
3375         /*
3376          * Check if it's a transparent hugepage. If this would be an
3377          * hugetlbfs page, level wouldn't be set to
3378          * PT_PAGE_TABLE_LEVEL and there would be no adjustment done
3379          * here.
3380          */
3381         if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn) &&
3382             level == PT_PAGE_TABLE_LEVEL &&
3383             PageTransCompoundMap(pfn_to_page(pfn)) &&
3384             !mmu_gfn_lpage_is_disallowed(vcpu, gfn, PT_DIRECTORY_LEVEL)) {
3385                 unsigned long mask;
3386                 /*
3387                  * mmu_notifier_retry was successful and we hold the
3388                  * mmu_lock here, so the pmd can't become splitting
3389                  * from under us, and in turn
3390                  * __split_huge_page_refcount() can't run from under
3391                  * us and we can safely transfer the refcount from
3392                  * PG_tail to PG_head as we switch the pfn to tail to
3393                  * head.
3394                  */
3395                 *levelp = level = PT_DIRECTORY_LEVEL;
3396                 mask = KVM_PAGES_PER_HPAGE(level) - 1;
3397                 VM_BUG_ON((gfn & mask) != (pfn & mask));
3398                 if (pfn & mask) {
3399                         kvm_release_pfn_clean(pfn);
3400                         pfn &= ~mask;
3401                         kvm_get_pfn(pfn);
3402                         *pfnp = pfn;
3403                 }
3404         }
3405 }
3406
3407 static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
3408                                 kvm_pfn_t pfn, unsigned access, int *ret_val)
3409 {
3410         /* The pfn is invalid, report the error! */
3411         if (unlikely(is_error_pfn(pfn))) {
3412                 *ret_val = kvm_handle_bad_page(vcpu, gfn, pfn);
3413                 return true;
3414         }
3415
3416         if (unlikely(is_noslot_pfn(pfn)))
3417                 vcpu_cache_mmio_info(vcpu, gva, gfn,
3418                                      access & shadow_mmio_access_mask);
3419
3420         return false;
3421 }
3422
3423 static bool page_fault_can_be_fast(u32 error_code)
3424 {
3425         /*
3426          * Do not fix the mmio spte with invalid generation number which
3427          * need to be updated by slow page fault path.
3428          */
3429         if (unlikely(error_code & PFERR_RSVD_MASK))
3430                 return false;
3431
3432         /* See if the page fault is due to an NX violation */
3433         if (unlikely(((error_code & (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))
3434                       == (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))))
3435                 return false;
3436
3437         /*
3438          * #PF can be fast if:
3439          * 1. The shadow page table entry is not present, which could mean that
3440          *    the fault is potentially caused by access tracking (if enabled).
3441          * 2. The shadow page table entry is present and the fault
3442          *    is caused by write-protect, that means we just need change the W
3443          *    bit of the spte which can be done out of mmu-lock.
3444          *
3445          * However, if access tracking is disabled we know that a non-present
3446          * page must be a genuine page fault where we have to create a new SPTE.
3447          * So, if access tracking is disabled, we return true only for write
3448          * accesses to a present page.
3449          */
3450
3451         return shadow_acc_track_mask != 0 ||
3452                ((error_code & (PFERR_WRITE_MASK | PFERR_PRESENT_MASK))
3453                 == (PFERR_WRITE_MASK | PFERR_PRESENT_MASK));
3454 }
3455
3456 /*
3457  * Returns true if the SPTE was fixed successfully. Otherwise,
3458  * someone else modified the SPTE from its original value.
3459  */
3460 static bool
3461 fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
3462                         u64 *sptep, u64 old_spte, u64 new_spte)
3463 {
3464         gfn_t gfn;
3465
3466         WARN_ON(!sp->role.direct);
3467
3468         /*
3469          * Theoretically we could also set dirty bit (and flush TLB) here in
3470          * order to eliminate unnecessary PML logging. See comments in
3471          * set_spte. But fast_page_fault is very unlikely to happen with PML
3472          * enabled, so we do not do this. This might result in the same GPA
3473          * to be logged in PML buffer again when the write really happens, and
3474          * eventually to be called by mark_page_dirty twice. But it's also no
3475          * harm. This also avoids the TLB flush needed after setting dirty bit
3476          * so non-PML cases won't be impacted.
3477          *
3478          * Compare with set_spte where instead shadow_dirty_mask is set.
3479          */
3480         if (cmpxchg64(sptep, old_spte, new_spte) != old_spte)
3481                 return false;
3482
3483         if (is_writable_pte(new_spte) && !is_writable_pte(old_spte)) {
3484                 /*
3485                  * The gfn of direct spte is stable since it is
3486                  * calculated by sp->gfn.
3487                  */
3488                 gfn = kvm_mmu_page_get_gfn(sp, sptep - sp->spt);
3489                 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3490         }
3491
3492         return true;
3493 }
3494
3495 static bool is_access_allowed(u32 fault_err_code, u64 spte)
3496 {
3497         if (fault_err_code & PFERR_FETCH_MASK)
3498                 return is_executable_pte(spte);
3499
3500         if (fault_err_code & PFERR_WRITE_MASK)
3501                 return is_writable_pte(spte);
3502
3503         /* Fault was on Read access */
3504         return spte & PT_PRESENT_MASK;
3505 }
3506
3507 /*
3508  * Return value:
3509  * - true: let the vcpu to access on the same address again.
3510  * - false: let the real page fault path to fix it.
3511  */
3512 static bool fast_page_fault(struct kvm_vcpu *vcpu, gva_t gva, int level,
3513                             u32 error_code)
3514 {
3515         struct kvm_shadow_walk_iterator iterator;
3516         struct kvm_mmu_page *sp;
3517         bool fault_handled = false;
3518         u64 spte = 0ull;
3519         uint retry_count = 0;
3520
3521         if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3522                 return false;
3523
3524         if (!page_fault_can_be_fast(error_code))
3525                 return false;
3526
3527         walk_shadow_page_lockless_begin(vcpu);
3528
3529         do {
3530                 u64 new_spte;
3531
3532                 for_each_shadow_entry_lockless(vcpu, gva, iterator, spte)
3533                         if (!is_shadow_present_pte(spte) ||
3534                             iterator.level < level)
3535                                 break;
3536
3537                 sp = page_header(__pa(iterator.sptep));
3538                 if (!is_last_spte(spte, sp->role.level))
3539                         break;
3540
3541                 /*
3542                  * Check whether the memory access that caused the fault would
3543                  * still cause it if it were to be performed right now. If not,
3544                  * then this is a spurious fault caused by TLB lazily flushed,
3545                  * or some other CPU has already fixed the PTE after the
3546                  * current CPU took the fault.
3547                  *
3548                  * Need not check the access of upper level table entries since
3549                  * they are always ACC_ALL.
3550                  */
3551                 if (is_access_allowed(error_code, spte)) {
3552                         fault_handled = true;
3553                         break;
3554                 }
3555
3556                 new_spte = spte;
3557
3558                 if (is_access_track_spte(spte))
3559                         new_spte = restore_acc_track_spte(new_spte);
3560
3561                 /*
3562                  * Currently, to simplify the code, write-protection can
3563                  * be removed in the fast path only if the SPTE was
3564                  * write-protected for dirty-logging or access tracking.
3565                  */
3566                 if ((error_code & PFERR_WRITE_MASK) &&
3567                     spte_can_locklessly_be_made_writable(spte))
3568                 {
3569                         new_spte |= PT_WRITABLE_MASK;
3570
3571                         /*
3572                          * Do not fix write-permission on the large spte.  Since