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