150d982ec1d264b6eaa555a8f9ac2be1ddfb1ab0
[linux-2.6-microblaze.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 {
4169         kvm_pfn_t pfn;
4170         int r;
4171         int level;
4172         bool force_pt_level;
4173         gfn_t gfn = gpa >> PAGE_SHIFT;
4174         unsigned long mmu_seq;
4175         int write = error_code & PFERR_WRITE_MASK;
4176         bool map_writable;
4177
4178         MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa));
4179
4180         if (page_fault_handle_page_track(vcpu, error_code, gfn))
4181                 return RET_PF_EMULATE;
4182
4183         r = mmu_topup_memory_caches(vcpu);
4184         if (r)
4185                 return r;
4186
4187         force_pt_level = !check_hugepage_cache_consistency(vcpu, gfn,
4188                                                            PT_DIRECTORY_LEVEL);
4189         level = mapping_level(vcpu, gfn, &force_pt_level);
4190         if (likely(!force_pt_level)) {
4191                 if (level > PT_DIRECTORY_LEVEL &&
4192                     !check_hugepage_cache_consistency(vcpu, gfn, level))
4193                         level = PT_DIRECTORY_LEVEL;
4194                 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
4195         }
4196
4197         if (fast_page_fault(vcpu, gpa, level, error_code))
4198                 return RET_PF_RETRY;
4199
4200         mmu_seq = vcpu->kvm->mmu_notifier_seq;
4201         smp_rmb();
4202
4203         if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
4204                 return RET_PF_RETRY;
4205
4206         if (handle_abnormal_pfn(vcpu, 0, gfn, pfn, ACC_ALL, &r))
4207                 return r;
4208
4209         r = RET_PF_RETRY;
4210         spin_lock(&vcpu->kvm->mmu_lock);
4211         if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
4212                 goto out_unlock;
4213         if (make_mmu_pages_available(vcpu) < 0)
4214                 goto out_unlock;
4215         if (likely(!force_pt_level))
4216                 transparent_hugepage_adjust(vcpu, gfn, &pfn, &level);
4217         r = __direct_map(vcpu, gpa, write, map_writable, level, pfn, prefault);
4218 out_unlock:
4219         spin_unlock(&vcpu->kvm->mmu_lock);
4220         kvm_release_pfn_clean(pfn);
4221         return r;
4222 }
4223
4224 static void nonpaging_init_context(struct kvm_vcpu *vcpu,
4225                                    struct kvm_mmu *context)
4226 {
4227         context->page_fault = nonpaging_page_fault;
4228         context->gva_to_gpa = nonpaging_gva_to_gpa;
4229         context->sync_page = nonpaging_sync_page;
4230         context->invlpg = nonpaging_invlpg;
4231         context->update_pte = nonpaging_update_pte;
4232         context->root_level = 0;
4233         context->shadow_root_level = PT32E_ROOT_LEVEL;
4234         context->direct_map = true;
4235         context->nx = false;
4236 }
4237
4238 /*
4239  * Find out if a previously cached root matching the new CR3/role is available.
4240  * The current root is also inserted into the cache.
4241  * If a matching root was found, it is assigned to kvm_mmu->root_hpa and true is
4242  * returned.
4243  * Otherwise, the LRU root from the cache is assigned to kvm_mmu->root_hpa and
4244  * false is returned. This root should now be freed by the caller.
4245  */
4246 static bool cached_root_available(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4247                                   union kvm_mmu_page_role new_role)
4248 {
4249         uint i;
4250         struct kvm_mmu_root_info root;
4251         struct kvm_mmu *mmu = vcpu->arch.mmu;
4252
4253         root.cr3 = mmu->root_cr3;
4254         root.hpa = mmu->root_hpa;
4255
4256         for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
4257                 swap(root, mmu->prev_roots[i]);
4258
4259                 if (new_cr3 == root.cr3 && VALID_PAGE(root.hpa) &&
4260                     page_header(root.hpa) != NULL &&
4261                     new_role.word == page_header(root.hpa)->role.word)
4262                         break;
4263         }
4264
4265         mmu->root_hpa = root.hpa;
4266         mmu->root_cr3 = root.cr3;
4267
4268         return i < KVM_MMU_NUM_PREV_ROOTS;
4269 }
4270
4271 static bool fast_cr3_switch(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4272                             union kvm_mmu_page_role new_role,
4273                             bool skip_tlb_flush)
4274 {
4275         struct kvm_mmu *mmu = vcpu->arch.mmu;
4276
4277         /*
4278          * For now, limit the fast switch to 64-bit hosts+VMs in order to avoid
4279          * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
4280          * later if necessary.
4281          */
4282         if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
4283             mmu->root_level >= PT64_ROOT_4LEVEL) {
4284                 if (mmu_check_root(vcpu, new_cr3 >> PAGE_SHIFT))
4285                         return false;
4286
4287                 if (cached_root_available(vcpu, new_cr3, new_role)) {
4288                         /*
4289                          * It is possible that the cached previous root page is
4290                          * obsolete because of a change in the MMU generation
4291                          * number. However, changing the generation number is
4292                          * accompanied by KVM_REQ_MMU_RELOAD, which will free
4293                          * the root set here and allocate a new one.
4294                          */
4295                         kvm_make_request(KVM_REQ_LOAD_CR3, vcpu);
4296                         if (!skip_tlb_flush) {
4297                                 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4298                                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
4299                         }
4300
4301                         /*
4302                          * The last MMIO access's GVA and GPA are cached in the
4303                          * VCPU. When switching to a new CR3, that GVA->GPA
4304                          * mapping may no longer be valid. So clear any cached
4305                          * MMIO info even when we don't need to sync the shadow
4306                          * page tables.
4307                          */
4308                         vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4309
4310                         __clear_sp_write_flooding_count(
4311                                 page_header(mmu->root_hpa));
4312
4313                         return true;
4314                 }
4315         }
4316
4317         return false;
4318 }
4319
4320 static void __kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4321                               union kvm_mmu_page_role new_role,
4322                               bool skip_tlb_flush)
4323 {
4324         if (!fast_cr3_switch(vcpu, new_cr3, new_role, skip_tlb_flush))
4325                 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu,
4326                                    KVM_MMU_ROOT_CURRENT);
4327 }
4328
4329 void kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3, bool skip_tlb_flush)
4330 {
4331         __kvm_mmu_new_cr3(vcpu, new_cr3, kvm_mmu_calc_root_page_role(vcpu),
4332                           skip_tlb_flush);
4333 }
4334 EXPORT_SYMBOL_GPL(kvm_mmu_new_cr3);
4335
4336 static unsigned long get_cr3(struct kvm_vcpu *vcpu)
4337 {
4338         return kvm_read_cr3(vcpu);
4339 }
4340
4341 static void inject_page_fault(struct kvm_vcpu *vcpu,
4342                               struct x86_exception *fault)
4343 {
4344         vcpu->arch.mmu->inject_page_fault(vcpu, fault);
4345 }
4346
4347 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4348                            unsigned access, int *nr_present)
4349 {
4350         if (unlikely(is_mmio_spte(*sptep))) {
4351                 if (gfn != get_mmio_spte_gfn(*sptep)) {
4352                         mmu_spte_clear_no_track(sptep);
4353                         return true;
4354                 }
4355
4356                 (*nr_present)++;
4357                 mark_mmio_spte(vcpu, sptep, gfn, access);
4358                 return true;
4359         }
4360
4361         return false;
4362 }
4363
4364 static inline bool is_last_gpte(struct kvm_mmu *mmu,
4365                                 unsigned level, unsigned gpte)
4366 {
4367         /*
4368          * The RHS has bit 7 set iff level < mmu->last_nonleaf_level.
4369          * If it is clear, there are no large pages at this level, so clear
4370          * PT_PAGE_SIZE_MASK in gpte if that is the case.
4371          */
4372         gpte &= level - mmu->last_nonleaf_level;
4373
4374         /*
4375          * PT_PAGE_TABLE_LEVEL always terminates.  The RHS has bit 7 set
4376          * iff level <= PT_PAGE_TABLE_LEVEL, which for our purpose means
4377          * level == PT_PAGE_TABLE_LEVEL; set PT_PAGE_SIZE_MASK in gpte then.
4378          */
4379         gpte |= level - PT_PAGE_TABLE_LEVEL - 1;
4380
4381         return gpte & PT_PAGE_SIZE_MASK;
4382 }
4383
4384 #define PTTYPE_EPT 18 /* arbitrary */
4385 #define PTTYPE PTTYPE_EPT
4386 #include "paging_tmpl.h"
4387 #undef PTTYPE
4388
4389 #define PTTYPE 64
4390 #include "paging_tmpl.h"
4391 #undef PTTYPE
4392
4393 #define PTTYPE 32
4394 #include "paging_tmpl.h"
4395 #undef PTTYPE
4396
4397 static void
4398 __reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4399                         struct rsvd_bits_validate *rsvd_check,
4400                         int maxphyaddr, int level, bool nx, bool gbpages,
4401                         bool pse, bool amd)
4402 {
4403         u64 exb_bit_rsvd = 0;
4404         u64 gbpages_bit_rsvd = 0;
4405         u64 nonleaf_bit8_rsvd = 0;
4406
4407         rsvd_check->bad_mt_xwr = 0;
4408
4409         if (!nx)
4410                 exb_bit_rsvd = rsvd_bits(63, 63);
4411         if (!gbpages)
4412                 gbpages_bit_rsvd = rsvd_bits(7, 7);
4413
4414         /*
4415          * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4416          * leaf entries) on AMD CPUs only.
4417          */
4418         if (amd)
4419                 nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4420
4421         switch (level) {
4422         case PT32_ROOT_LEVEL:
4423                 /* no rsvd bits for 2 level 4K page table entries */
4424                 rsvd_check->rsvd_bits_mask[0][1] = 0;
4425                 rsvd_check->rsvd_bits_mask[0][0] = 0;
4426                 rsvd_check->rsvd_bits_mask[1][0] =
4427                         rsvd_check->rsvd_bits_mask[0][0];
4428
4429                 if (!pse) {
4430                         rsvd_check->rsvd_bits_mask[1][1] = 0;
4431                         break;
4432                 }
4433
4434                 if (is_cpuid_PSE36())
4435                         /* 36bits PSE 4MB page */
4436                         rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4437                 else
4438                         /* 32 bits PSE 4MB page */
4439                         rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4440                 break;
4441         case PT32E_ROOT_LEVEL:
4442                 rsvd_check->rsvd_bits_mask[0][2] =
4443                         rsvd_bits(maxphyaddr, 63) |
4444                         rsvd_bits(5, 8) | rsvd_bits(1, 2);      /* PDPTE */
4445                 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4446                         rsvd_bits(maxphyaddr, 62);      /* PDE */
4447                 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4448                         rsvd_bits(maxphyaddr, 62);      /* PTE */
4449                 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4450                         rsvd_bits(maxphyaddr, 62) |
4451                         rsvd_bits(13, 20);              /* large page */
4452                 rsvd_check->rsvd_bits_mask[1][0] =
4453                         rsvd_check->rsvd_bits_mask[0][0];
4454                 break;
4455         case PT64_ROOT_5LEVEL:
4456                 rsvd_check->rsvd_bits_mask[0][4] = exb_bit_rsvd |
4457                         nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4458                         rsvd_bits(maxphyaddr, 51);
4459                 rsvd_check->rsvd_bits_mask[1][4] =
4460                         rsvd_check->rsvd_bits_mask[0][4];
4461                 /* fall through */
4462         case PT64_ROOT_4LEVEL:
4463                 rsvd_check->rsvd_bits_mask[0][3] = exb_bit_rsvd |
4464                         nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4465                         rsvd_bits(maxphyaddr, 51);
4466                 rsvd_check->rsvd_bits_mask[0][2] = exb_bit_rsvd |
4467                         nonleaf_bit8_rsvd | gbpages_bit_rsvd |
4468                         rsvd_bits(maxphyaddr, 51);
4469                 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4470                         rsvd_bits(maxphyaddr, 51);
4471                 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4472                         rsvd_bits(maxphyaddr, 51);
4473                 rsvd_check->rsvd_bits_mask[1][3] =
4474                         rsvd_check->rsvd_bits_mask[0][3];
4475                 rsvd_check->rsvd_bits_mask[1][2] = exb_bit_rsvd |
4476                         gbpages_bit_rsvd | rsvd_bits(maxphyaddr, 51) |
4477                         rsvd_bits(13, 29);
4478                 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4479                         rsvd_bits(maxphyaddr, 51) |
4480                         rsvd_bits(13, 20);              /* large page */
4481                 rsvd_check->rsvd_bits_mask[1][0] =
4482                         rsvd_check->rsvd_bits_mask[0][0];
4483                 break;
4484         }
4485 }
4486
4487 static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4488                                   struct kvm_mmu *context)
4489 {
4490         __reset_rsvds_bits_mask(vcpu, &context->guest_rsvd_check,
4491                                 cpuid_maxphyaddr(vcpu), context->root_level,
4492                                 context->nx,
4493                                 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4494                                 is_pse(vcpu), guest_cpuid_is_amd(vcpu));
4495 }
4496
4497 static void
4498 __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
4499                             int maxphyaddr, bool execonly)
4500 {
4501         u64 bad_mt_xwr;
4502
4503         rsvd_check->rsvd_bits_mask[0][4] =
4504                 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4505         rsvd_check->rsvd_bits_mask[0][3] =
4506                 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4507         rsvd_check->rsvd_bits_mask[0][2] =
4508                 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4509         rsvd_check->rsvd_bits_mask[0][1] =
4510                 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4511         rsvd_check->rsvd_bits_mask[0][0] = rsvd_bits(maxphyaddr, 51);
4512
4513         /* large page */
4514         rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4515         rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
4516         rsvd_check->rsvd_bits_mask[1][2] =
4517                 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 29);
4518         rsvd_check->rsvd_bits_mask[1][1] =
4519                 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 20);
4520         rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4521
4522         bad_mt_xwr = 0xFFull << (2 * 8);        /* bits 3..5 must not be 2 */
4523         bad_mt_xwr |= 0xFFull << (3 * 8);       /* bits 3..5 must not be 3 */
4524         bad_mt_xwr |= 0xFFull << (7 * 8);       /* bits 3..5 must not be 7 */
4525         bad_mt_xwr |= REPEAT_BYTE(1ull << 2);   /* bits 0..2 must not be 010 */
4526         bad_mt_xwr |= REPEAT_BYTE(1ull << 6);   /* bits 0..2 must not be 110 */
4527         if (!execonly) {
4528                 /* bits 0..2 must not be 100 unless VMX capabilities allow it */
4529                 bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4530         }
4531         rsvd_check->bad_mt_xwr = bad_mt_xwr;
4532 }
4533
4534 static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
4535                 struct kvm_mmu *context, bool execonly)
4536 {
4537         __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
4538                                     cpuid_maxphyaddr(vcpu), execonly);
4539 }
4540
4541 /*
4542  * the page table on host is the shadow page table for the page
4543  * table in guest or amd nested guest, its mmu features completely
4544  * follow the features in guest.
4545  */
4546 void
4547 reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
4548 {
4549         bool uses_nx = context->nx ||
4550                 context->mmu_role.base.smep_andnot_wp;
4551         struct rsvd_bits_validate *shadow_zero_check;
4552         int i;
4553
4554         /*
4555          * Passing "true" to the last argument is okay; it adds a check
4556          * on bit 8 of the SPTEs which KVM doesn't use anyway.
4557          */
4558         shadow_zero_check = &context->shadow_zero_check;
4559         __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4560                                 shadow_phys_bits,
4561                                 context->shadow_root_level, uses_nx,
4562                                 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4563                                 is_pse(vcpu), true);
4564
4565         if (!shadow_me_mask)
4566                 return;
4567
4568         for (i = context->shadow_root_level; --i >= 0;) {
4569                 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4570                 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4571         }
4572
4573 }
4574 EXPORT_SYMBOL_GPL(reset_shadow_zero_bits_mask);
4575
4576 static inline bool boot_cpu_is_amd(void)
4577 {
4578         WARN_ON_ONCE(!tdp_enabled);
4579         return shadow_x_mask == 0;
4580 }
4581
4582 /*
4583  * the direct page table on host, use as much mmu features as
4584  * possible, however, kvm currently does not do execution-protection.
4585  */
4586 static void
4587 reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4588                                 struct kvm_mmu *context)
4589 {
4590         struct rsvd_bits_validate *shadow_zero_check;
4591         int i;
4592
4593         shadow_zero_check = &context->shadow_zero_check;
4594
4595         if (boot_cpu_is_amd())
4596                 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4597                                         shadow_phys_bits,
4598                                         context->shadow_root_level, false,
4599                                         boot_cpu_has(X86_FEATURE_GBPAGES),
4600                                         true, true);
4601         else
4602                 __reset_rsvds_bits_mask_ept(shadow_zero_check,
4603                                             shadow_phys_bits,
4604                                             false);
4605
4606         if (!shadow_me_mask)
4607                 return;
4608
4609         for (i = context->shadow_root_level; --i >= 0;) {
4610                 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4611                 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4612         }
4613 }
4614
4615 /*
4616  * as the comments in reset_shadow_zero_bits_mask() except it
4617  * is the shadow page table for intel nested guest.
4618  */
4619 static void
4620 reset_ept_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4621                                 struct kvm_mmu *context, bool execonly)
4622 {
4623         __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
4624                                     shadow_phys_bits, execonly);
4625 }
4626
4627 #define BYTE_MASK(access) \
4628         ((1 & (access) ? 2 : 0) | \
4629          (2 & (access) ? 4 : 0) | \
4630          (3 & (access) ? 8 : 0) | \
4631          (4 & (access) ? 16 : 0) | \
4632          (5 & (access) ? 32 : 0) | \
4633          (6 & (access) ? 64 : 0) | \
4634          (7 & (access) ? 128 : 0))
4635
4636
4637 static void update_permission_bitmask(struct kvm_vcpu *vcpu,
4638                                       struct kvm_mmu *mmu, bool ept)
4639 {
4640         unsigned byte;
4641
4642         const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4643         const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4644         const u8 u = BYTE_MASK(ACC_USER_MASK);
4645
4646         bool cr4_smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP) != 0;
4647         bool cr4_smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP) != 0;
4648         bool cr0_wp = is_write_protection(vcpu);
4649
4650         for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
4651                 unsigned pfec = byte << 1;
4652
4653                 /*
4654                  * Each "*f" variable has a 1 bit for each UWX value
4655                  * that causes a fault with the given PFEC.
4656                  */
4657
4658                 /* Faults from writes to non-writable pages */
4659                 u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
4660                 /* Faults from user mode accesses to supervisor pages */
4661                 u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
4662                 /* Faults from fetches of non-executable pages*/
4663                 u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
4664                 /* Faults from kernel mode fetches of user pages */
4665                 u8 smepf = 0;
4666                 /* Faults from kernel mode accesses of user pages */
4667                 u8 smapf = 0;
4668
4669                 if (!ept) {
4670                         /* Faults from kernel mode accesses to user pages */
4671                         u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
4672
4673                         /* Not really needed: !nx will cause pte.nx to fault */
4674                         if (!mmu->nx)
4675                                 ff = 0;
4676
4677                         /* Allow supervisor writes if !cr0.wp */
4678                         if (!cr0_wp)
4679                                 wf = (pfec & PFERR_USER_MASK) ? wf : 0;
4680
4681                         /* Disallow supervisor fetches of user code if cr4.smep */
4682                         if (cr4_smep)
4683                                 smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
4684
4685                         /*
4686                          * SMAP:kernel-mode data accesses from user-mode
4687                          * mappings should fault. A fault is considered
4688                          * as a SMAP violation if all of the following
4689                          * conditions are true:
4690                          *   - X86_CR4_SMAP is set in CR4
4691                          *   - A user page is accessed
4692                          *   - The access is not a fetch
4693                          *   - Page fault in kernel mode
4694                          *   - if CPL = 3 or X86_EFLAGS_AC is clear
4695                          *
4696                          * Here, we cover the first three conditions.
4697                          * The fourth is computed dynamically in permission_fault();
4698                          * PFERR_RSVD_MASK bit will be set in PFEC if the access is
4699                          * *not* subject to SMAP restrictions.
4700                          */
4701                         if (cr4_smap)
4702                                 smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
4703                 }
4704
4705                 mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
4706         }
4707 }
4708
4709 /*
4710 * PKU is an additional mechanism by which the paging controls access to
4711 * user-mode addresses based on the value in the PKRU register.  Protection
4712 * key violations are reported through a bit in the page fault error code.
4713 * Unlike other bits of the error code, the PK bit is not known at the
4714 * call site of e.g. gva_to_gpa; it must be computed directly in
4715 * permission_fault based on two bits of PKRU, on some machine state (CR4,
4716 * CR0, EFER, CPL), and on other bits of the error code and the page tables.
4717 *
4718 * In particular the following conditions come from the error code, the
4719 * page tables and the machine state:
4720 * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
4721 * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
4722 * - PK is always zero if U=0 in the page tables
4723 * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
4724 *
4725 * The PKRU bitmask caches the result of these four conditions.  The error
4726 * code (minus the P bit) and the page table's U bit form an index into the
4727 * PKRU bitmask.  Two bits of the PKRU bitmask are then extracted and ANDed
4728 * with the two bits of the PKRU register corresponding to the protection key.
4729 * For the first three conditions above the bits will be 00, thus masking
4730 * away both AD and WD.  For all reads or if the last condition holds, WD
4731 * only will be masked away.
4732 */
4733 static void update_pkru_bitmask(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
4734                                 bool ept)
4735 {
4736         unsigned bit;
4737         bool wp;
4738
4739         if (ept) {
4740                 mmu->pkru_mask = 0;
4741                 return;
4742         }
4743
4744         /* PKEY is enabled only if CR4.PKE and EFER.LMA are both set. */
4745         if (!kvm_read_cr4_bits(vcpu, X86_CR4_PKE) || !is_long_mode(vcpu)) {
4746                 mmu->pkru_mask = 0;
4747                 return;
4748         }
4749
4750         wp = is_write_protection(vcpu);
4751
4752         for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
4753                 unsigned pfec, pkey_bits;
4754                 bool check_pkey, check_write, ff, uf, wf, pte_user;
4755
4756                 pfec = bit << 1;
4757                 ff = pfec & PFERR_FETCH_MASK;
4758                 uf = pfec & PFERR_USER_MASK;
4759                 wf = pfec & PFERR_WRITE_MASK;
4760
4761                 /* PFEC.RSVD is replaced by ACC_USER_MASK. */
4762                 pte_user = pfec & PFERR_RSVD_MASK;
4763
4764                 /*
4765                  * Only need to check the access which is not an
4766                  * instruction fetch and is to a user page.
4767                  */
4768                 check_pkey = (!ff && pte_user);
4769                 /*
4770                  * write access is controlled by PKRU if it is a
4771                  * user access or CR0.WP = 1.
4772                  */
4773                 check_write = check_pkey && wf && (uf || wp);
4774
4775                 /* PKRU.AD stops both read and write access. */
4776                 pkey_bits = !!check_pkey;
4777                 /* PKRU.WD stops write access. */
4778                 pkey_bits |= (!!check_write) << 1;
4779
4780                 mmu->pkru_mask |= (pkey_bits & 3) << pfec;
4781         }
4782 }
4783
4784 static void update_last_nonleaf_level(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
4785 {
4786         unsigned root_level = mmu->root_level;
4787
4788         mmu->last_nonleaf_level = root_level;
4789         if (root_level == PT32_ROOT_LEVEL && is_pse(vcpu))
4790                 mmu->last_nonleaf_level++;
4791 }
4792
4793 static void paging64_init_context_common(struct kvm_vcpu *vcpu,
4794                                          struct kvm_mmu *context,
4795                                          int level)
4796 {
4797         context->nx = is_nx(vcpu);
4798         context->root_level = level;
4799
4800         reset_rsvds_bits_mask(vcpu, context);
4801         update_permission_bitmask(vcpu, context, false);
4802         update_pkru_bitmask(vcpu, context, false);
4803         update_last_nonleaf_level(vcpu, context);
4804
4805         MMU_WARN_ON(!is_pae(vcpu));
4806         context->page_fault = paging64_page_fault;
4807         context->gva_to_gpa = paging64_gva_to_gpa;
4808         context->sync_page = paging64_sync_page;
4809         context->invlpg = paging64_invlpg;
4810         context->update_pte = paging64_update_pte;
4811         context->shadow_root_level = level;
4812         context->direct_map = false;
4813 }
4814
4815 static void paging64_init_context(struct kvm_vcpu *vcpu,
4816                                   struct kvm_mmu *context)
4817 {
4818         int root_level = is_la57_mode(vcpu) ?
4819                          PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4820
4821         paging64_init_context_common(vcpu, context, root_level);
4822 }
4823
4824 static void paging32_init_context(struct kvm_vcpu *vcpu,
4825                                   struct kvm_mmu *context)
4826 {
4827         context->nx = false;
4828         context->root_level = PT32_ROOT_LEVEL;
4829
4830         reset_rsvds_bits_mask(vcpu, context);
4831         update_permission_bitmask(vcpu, context, false);
4832         update_pkru_bitmask(vcpu, context, false);
4833         update_last_nonleaf_level(vcpu, context);
4834
4835         context->page_fault = paging32_page_fault;
4836         context->gva_to_gpa = paging32_gva_to_gpa;
4837         context->sync_page = paging32_sync_page;
4838         context->invlpg = paging32_invlpg;
4839         context->update_pte = paging32_update_pte;
4840         context->shadow_root_level = PT32E_ROOT_LEVEL;
4841         context->direct_map = false;
4842 }
4843
4844 static void paging32E_init_context(struct kvm_vcpu *vcpu,
4845                                    struct kvm_mmu *context)
4846 {
4847         paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
4848 }
4849
4850 static union kvm_mmu_extended_role kvm_calc_mmu_role_ext(struct kvm_vcpu *vcpu)
4851 {
4852         union kvm_mmu_extended_role ext = {0};
4853
4854         ext.cr0_pg = !!is_paging(vcpu);
4855         ext.cr4_pae = !!is_pae(vcpu);
4856         ext.cr4_smep = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
4857         ext.cr4_smap = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
4858         ext.cr4_pse = !!is_pse(vcpu);
4859         ext.cr4_pke = !!kvm_read_cr4_bits(vcpu, X86_CR4_PKE);
4860         ext.cr4_la57 = !!kvm_read_cr4_bits(vcpu, X86_CR4_LA57);
4861         ext.maxphyaddr = cpuid_maxphyaddr(vcpu);
4862
4863         ext.valid = 1;
4864
4865         return ext;
4866 }
4867
4868 static union kvm_mmu_role kvm_calc_mmu_role_common(struct kvm_vcpu *vcpu,
4869                                                    bool base_only)
4870 {
4871         union kvm_mmu_role role = {0};
4872
4873         role.base.access = ACC_ALL;
4874         role.base.nxe = !!is_nx(vcpu);
4875         role.base.cr0_wp = is_write_protection(vcpu);
4876         role.base.smm = is_smm(vcpu);
4877         role.base.guest_mode = is_guest_mode(vcpu);
4878
4879         if (base_only)
4880                 return role;
4881
4882         role.ext = kvm_calc_mmu_role_ext(vcpu);
4883
4884         return role;
4885 }
4886
4887 static union kvm_mmu_role
4888 kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4889 {
4890         union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4891
4892         role.base.ad_disabled = (shadow_accessed_mask == 0);
4893         role.base.level = kvm_x86_ops->get_tdp_level(vcpu);
4894         role.base.direct = true;
4895         role.base.gpte_is_8_bytes = true;
4896
4897         return role;
4898 }
4899
4900 static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
4901 {
4902         struct kvm_mmu *context = vcpu->arch.mmu;
4903         union kvm_mmu_role new_role =
4904                 kvm_calc_tdp_mmu_root_page_role(vcpu, false);
4905
4906         new_role.base.word &= mmu_base_role_mask.word;
4907         if (new_role.as_u64 == context->mmu_role.as_u64)
4908                 return;
4909
4910         context->mmu_role.as_u64 = new_role.as_u64;
4911         context->page_fault = tdp_page_fault;
4912         context->sync_page = nonpaging_sync_page;
4913         context->invlpg = nonpaging_invlpg;
4914         context->update_pte = nonpaging_update_pte;
4915         context->shadow_root_level = kvm_x86_ops->get_tdp_level(vcpu);
4916         context->direct_map = true;
4917         context->set_cr3 = kvm_x86_ops->set_tdp_cr3;
4918         context->get_cr3 = get_cr3;
4919         context->get_pdptr = kvm_pdptr_read;
4920         context->inject_page_fault = kvm_inject_page_fault;
4921
4922         if (!is_paging(vcpu)) {
4923                 context->nx = false;
4924                 context->gva_to_gpa = nonpaging_gva_to_gpa;
4925                 context->root_level = 0;
4926         } else if (is_long_mode(vcpu)) {
4927                 context->nx = is_nx(vcpu);
4928                 context->root_level = is_la57_mode(vcpu) ?
4929                                 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4930                 reset_rsvds_bits_mask(vcpu, context);
4931                 context->gva_to_gpa = paging64_gva_to_gpa;
4932         } else if (is_pae(vcpu)) {
4933                 context->nx = is_nx(vcpu);
4934                 context->root_level = PT32E_ROOT_LEVEL;
4935                 reset_rsvds_bits_mask(vcpu, context);
4936                 context->gva_to_gpa = paging64_gva_to_gpa;
4937         } else {
4938                 context->nx = false;
4939                 context->root_level = PT32_ROOT_LEVEL;
4940                 reset_rsvds_bits_mask(vcpu, context);
4941                 context->gva_to_gpa = paging32_gva_to_gpa;
4942         }
4943
4944         update_permission_bitmask(vcpu, context, false);
4945         update_pkru_bitmask(vcpu, context, false);
4946         update_last_nonleaf_level(vcpu, context);
4947         reset_tdp_shadow_zero_bits_mask(vcpu, context);
4948 }
4949
4950 static union kvm_mmu_role
4951 kvm_calc_shadow_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4952 {
4953         union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4954
4955         role.base.smep_andnot_wp = role.ext.cr4_smep &&
4956                 !is_write_protection(vcpu);
4957         role.base.smap_andnot_wp = role.ext.cr4_smap &&
4958                 !is_write_protection(vcpu);
4959         role.base.direct = !is_paging(vcpu);
4960         role.base.gpte_is_8_bytes = !!is_pae(vcpu);
4961
4962         if (!is_long_mode(vcpu))
4963                 role.base.level = PT32E_ROOT_LEVEL;
4964         else if (is_la57_mode(vcpu))
4965                 role.base.level = PT64_ROOT_5LEVEL;
4966         else
4967                 role.base.level = PT64_ROOT_4LEVEL;
4968
4969         return role;
4970 }
4971
4972 void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu)
4973 {
4974         struct kvm_mmu *context = vcpu->arch.mmu;
4975         union kvm_mmu_role new_role =
4976                 kvm_calc_shadow_mmu_root_page_role(vcpu, false);
4977
4978         new_role.base.word &= mmu_base_role_mask.word;
4979         if (new_role.as_u64 == context->mmu_role.as_u64)
4980                 return;
4981
4982         if (!is_paging(vcpu))
4983                 nonpaging_init_context(vcpu, context);
4984         else if (is_long_mode(vcpu))
4985                 paging64_init_context(vcpu, context);
4986         else if (is_pae(vcpu))
4987                 paging32E_init_context(vcpu, context);
4988         else
4989                 paging32_init_context(vcpu, context);
4990
4991         context->mmu_role.as_u64 = new_role.as_u64;
4992         reset_shadow_zero_bits_mask(vcpu, context);
4993 }
4994 EXPORT_SYMBOL_GPL(kvm_init_shadow_mmu);
4995
4996 static union kvm_mmu_role
4997 kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
4998                                    bool execonly)
4999 {
5000         union kvm_mmu_role role = {0};
5001
5002         /* SMM flag is inherited from root_mmu */
5003         role.base.smm = vcpu->arch.root_mmu.mmu_role.base.smm;
5004
5005         role.base.level = PT64_ROOT_4LEVEL;
5006         role.base.gpte_is_8_bytes = true;
5007         role.base.direct = false;
5008         role.base.ad_disabled = !accessed_dirty;
5009         role.base.guest_mode = true;
5010         role.base.access = ACC_ALL;
5011
5012         /*
5013          * WP=1 and NOT_WP=1 is an impossible combination, use WP and the
5014          * SMAP variation to denote shadow EPT entries.
5015          */
5016         role.base.cr0_wp = true;
5017         role.base.smap_andnot_wp = true;
5018
5019         role.ext = kvm_calc_mmu_role_ext(vcpu);
5020         role.ext.execonly = execonly;
5021
5022         return role;
5023 }
5024
5025 void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
5026                              bool accessed_dirty, gpa_t new_eptp)
5027 {
5028         struct kvm_mmu *context = vcpu->arch.mmu;
5029         union kvm_mmu_role new_role =
5030                 kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
5031                                                    execonly);
5032
5033         __kvm_mmu_new_cr3(vcpu, new_eptp, new_role.base, false);
5034
5035         new_role.base.word &= mmu_base_role_mask.word;
5036         if (new_role.as_u64 == context->mmu_role.as_u64)
5037                 return;
5038
5039         context->shadow_root_level = PT64_ROOT_4LEVEL;
5040
5041         context->nx = true;
5042         context->ept_ad = accessed_dirty;
5043         context->page_fault = ept_page_fault;
5044         context->gva_to_gpa = ept_gva_to_gpa;
5045         context->sync_page = ept_sync_page;
5046         context->invlpg = ept_invlpg;
5047         context->update_pte = ept_update_pte;
5048         context->root_level = PT64_ROOT_4LEVEL;
5049         context->direct_map = false;
5050         context->mmu_role.as_u64 = new_role.as_u64;
5051
5052         update_permission_bitmask(vcpu, context, true);
5053         update_pkru_bitmask(vcpu, context, true);
5054         update_last_nonleaf_level(vcpu, context);
5055         reset_rsvds_bits_mask_ept(vcpu, context, execonly);
5056         reset_ept_shadow_zero_bits_mask(vcpu, context, execonly);
5057 }
5058 EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
5059
5060 static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
5061 {
5062         struct kvm_mmu *context = vcpu->arch.mmu;
5063
5064         kvm_init_shadow_mmu(vcpu);
5065         context->set_cr3           = kvm_x86_ops->set_cr3;
5066         context->get_cr3           = get_cr3;
5067         context->get_pdptr         = kvm_pdptr_read;
5068         context->inject_page_fault = kvm_inject_page_fault;
5069 }
5070
5071 static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
5072 {
5073         union kvm_mmu_role new_role = kvm_calc_mmu_role_common(vcpu, false);
5074         struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
5075
5076         new_role.base.word &= mmu_base_role_mask.word;
5077         if (new_role.as_u64 == g_context->mmu_role.as_u64)
5078                 return;
5079
5080         g_context->mmu_role.as_u64 = new_role.as_u64;
5081         g_context->get_cr3           = get_cr3;
5082         g_context->get_pdptr         = kvm_pdptr_read;
5083         g_context->inject_page_fault = kvm_inject_page_fault;
5084
5085         /*
5086          * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
5087          * L1's nested page tables (e.g. EPT12). The nested translation
5088          * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5089          * L2's page tables as the first level of translation and L1's
5090          * nested page tables as the second level of translation. Basically
5091          * the gva_to_gpa functions between mmu and nested_mmu are swapped.
5092          */
5093         if (!is_paging(vcpu)) {
5094                 g_context->nx = false;
5095                 g_context->root_level = 0;
5096                 g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
5097         } else if (is_long_mode(vcpu)) {
5098                 g_context->nx = is_nx(vcpu);
5099                 g_context->root_level = is_la57_mode(vcpu) ?
5100                                         PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
5101                 reset_rsvds_bits_mask(vcpu, g_context);
5102                 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5103         } else if (is_pae(vcpu)) {
5104                 g_context->nx = is_nx(vcpu);
5105                 g_context->root_level = PT32E_ROOT_LEVEL;
5106                 reset_rsvds_bits_mask(vcpu, g_context);
5107                 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5108         } else {
5109                 g_context->nx = false;
5110                 g_context->root_level = PT32_ROOT_LEVEL;
5111                 reset_rsvds_bits_mask(vcpu, g_context);
5112                 g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
5113         }
5114
5115         update_permission_bitmask(vcpu, g_context, false);
5116         update_pkru_bitmask(vcpu, g_context, false);
5117         update_last_nonleaf_level(vcpu, g_context);
5118 }
5119
5120 void kvm_init_mmu(struct kvm_vcpu *vcpu, bool reset_roots)
5121 {
5122         if (reset_roots) {
5123                 uint i;
5124
5125                 vcpu->arch.mmu->root_hpa = INVALID_PAGE;
5126
5127                 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5128                         vcpu->arch.mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5129         }
5130
5131         if (mmu_is_nested(vcpu))
5132                 init_kvm_nested_mmu(vcpu);
5133         else if (tdp_enabled)
5134                 init_kvm_tdp_mmu(vcpu);
5135         else
5136                 init_kvm_softmmu(vcpu);
5137 }
5138 EXPORT_SYMBOL_GPL(kvm_init_mmu);
5139
5140 static union kvm_mmu_page_role
5141 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu)
5142 {
5143         union kvm_mmu_role role;
5144
5145         if (tdp_enabled)
5146                 role = kvm_calc_tdp_mmu_root_page_role(vcpu, true);
5147         else
5148                 role = kvm_calc_shadow_mmu_root_page_role(vcpu, true);
5149
5150         return role.base;
5151 }
5152
5153 void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5154 {
5155         kvm_mmu_unload(vcpu);
5156         kvm_init_mmu(vcpu, true);
5157 }
5158 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5159
5160 int kvm_mmu_load(struct kvm_vcpu *vcpu)
5161 {
5162         int r;
5163
5164         r = mmu_topup_memory_caches(vcpu);
5165         if (r)
5166                 goto out;
5167         r = mmu_alloc_roots(vcpu);
5168         kvm_mmu_sync_roots(vcpu);
5169         if (r)
5170                 goto out;
5171         kvm_mmu_load_cr3(vcpu);
5172         kvm_x86_ops->tlb_flush(vcpu, true);
5173 out:
5174         return r;
5175 }
5176 EXPORT_SYMBOL_GPL(kvm_mmu_load);
5177
5178 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5179 {
5180         kvm_mmu_free_roots(vcpu, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
5181         WARN_ON(VALID_PAGE(vcpu->arch.root_mmu.root_hpa));
5182         kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
5183         WARN_ON(VALID_PAGE(vcpu->arch.guest_mmu.root_hpa));
5184 }
5185 EXPORT_SYMBOL_GPL(kvm_mmu_unload);
5186
5187 static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
5188                                   struct kvm_mmu_page *sp, u64 *spte,
5189                                   const void *new)
5190 {
5191         if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
5192                 ++vcpu->kvm->stat.mmu_pde_zapped;
5193                 return;
5194         }
5195
5196         ++vcpu->kvm->stat.mmu_pte_updated;
5197         vcpu->arch.mmu->update_pte(vcpu, sp, spte, new);
5198 }
5199
5200 static bool need_remote_flush(u64 old, u64 new)
5201 {
5202         if (!is_shadow_present_pte(old))
5203                 return false;
5204         if (!is_shadow_present_pte(new))
5205                 return true;
5206         if ((old ^ new) & PT64_BASE_ADDR_MASK)
5207                 return true;
5208         old ^= shadow_nx_mask;
5209         new ^= shadow_nx_mask;
5210         return (old & ~new & PT64_PERM_MASK) != 0;
5211 }
5212
5213 static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5214                                     int *bytes)
5215 {
5216         u64 gentry = 0;
5217         int r;
5218
5219         /*
5220          * Assume that the pte write on a page table of the same type
5221          * as the current vcpu paging mode since we update the sptes only
5222          * when they have the same mode.
5223          */
5224         if (is_pae(vcpu) && *bytes == 4) {
5225                 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5226                 *gpa &= ~(gpa_t)7;
5227                 *bytes = 8;
5228         }
5229
5230         if (*bytes == 4 || *bytes == 8) {
5231                 r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5232                 if (r)
5233                         gentry = 0;
5234         }
5235
5236         return gentry;
5237 }
5238
5239 /*
5240  * If we're seeing too many writes to a page, it may no longer be a page table,
5241  * or we may be forking, in which case it is better to unmap the page.
5242  */
5243 static bool detect_write_flooding(struct kvm_mmu_page *sp)
5244 {
5245         /*
5246          * Skip write-flooding detected for the sp whose level is 1, because
5247          * it can become unsync, then the guest page is not write-protected.
5248          */
5249         if (sp->role.level == PT_PAGE_TABLE_LEVEL)
5250                 return false;
5251
5252         atomic_inc(&sp->write_flooding_count);
5253         return atomic_read(&sp->write_flooding_count) >= 3;
5254 }
5255
5256 /*
5257  * Misaligned accesses are too much trouble to fix up; also, they usually
5258  * indicate a page is not used as a page table.
5259  */
5260 static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5261                                     int bytes)
5262 {
5263         unsigned offset, pte_size, misaligned;
5264
5265         pgprintk("misaligned: gpa %llx bytes %d role %x\n",
5266                  gpa, bytes, sp->role.word);
5267
5268         offset = offset_in_page(gpa);
5269         pte_size = sp->role.gpte_is_8_bytes ? 8 : 4;
5270
5271         /*
5272          * Sometimes, the OS only writes the last one bytes to update status
5273          * bits, for example, in linux, andb instruction is used in clear_bit().
5274          */
5275         if (!(offset & (pte_size - 1)) && bytes == 1)
5276                 return false;
5277
5278         misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5279         misaligned |= bytes < 4;
5280
5281         return misaligned;
5282 }
5283
5284 static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5285 {
5286         unsigned page_offset, quadrant;
5287         u64 *spte;
5288         int level;
5289
5290         page_offset = offset_in_page(gpa);
5291         level = sp->role.level;
5292         *nspte = 1;
5293         if (!sp->role.gpte_is_8_bytes) {
5294                 page_offset <<= 1;      /* 32->64 */
5295                 /*
5296                  * A 32-bit pde maps 4MB while the shadow pdes map
5297                  * only 2MB.  So we need to double the offset again
5298                  * and zap two pdes instead of one.
5299                  */
5300                 if (level == PT32_ROOT_LEVEL) {
5301                         page_offset &= ~7; /* kill rounding error */
5302                         page_offset <<= 1;
5303                         *nspte = 2;
5304                 }
5305                 quadrant = page_offset >> PAGE_SHIFT;
5306                 page_offset &= ~PAGE_MASK;
5307                 if (quadrant != sp->role.quadrant)
5308                         return NULL;
5309         }
5310
5311         spte = &sp->spt[page_offset / sizeof(*spte)];
5312         return spte;
5313 }
5314
5315 static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
5316                               const u8 *new, int bytes,
5317                               struct kvm_page_track_notifier_node *node)
5318 {
5319         gfn_t gfn = gpa >> PAGE_SHIFT;
5320         struct kvm_mmu_page *sp;
5321         LIST_HEAD(invalid_list);
5322         u64 entry, gentry, *spte;
5323         int npte;
5324         bool remote_flush, local_flush;
5325
5326         /*
5327          * If we don't have indirect shadow pages, it means no page is
5328          * write-protected, so we can exit simply.
5329          */
5330         if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
5331                 return;
5332
5333         remote_flush = local_flush = false;
5334
5335         pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
5336
5337         /*
5338          * No need to care whether allocation memory is successful
5339          * or not since pte prefetch is skiped if it does not have
5340          * enough objects in the cache.
5341          */
5342         mmu_topup_memory_caches(vcpu);
5343
5344         spin_lock(&vcpu->kvm->mmu_lock);
5345
5346         gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5347
5348         ++vcpu->kvm->stat.mmu_pte_write;
5349         kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
5350
5351         for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
5352                 if (detect_write_misaligned(sp, gpa, bytes) ||
5353                       detect_write_flooding(sp)) {
5354                         kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5355                         ++vcpu->kvm->stat.mmu_flooded;
5356                         continue;
5357                 }
5358
5359                 spte = get_written_sptes(sp, gpa, &npte);
5360                 if (!spte)
5361                         continue;
5362
5363                 local_flush = true;
5364                 while (npte--) {
5365                         u32 base_role = vcpu->arch.mmu->mmu_role.base.word;
5366
5367                         entry = *spte;
5368                         mmu_page_zap_pte(vcpu->kvm, sp, spte);
5369                         if (gentry &&
5370                               !((sp->role.word ^ base_role)
5371                               & mmu_base_role_mask.word) && rmap_can_add(vcpu))
5372                                 mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
5373                         if (need_remote_flush(entry, *spte))
5374                                 remote_flush = true;
5375                         ++spte;
5376                 }
5377         }
5378         kvm_mmu_flush_or_zap(vcpu, &invalid_list, remote_flush, local_flush);
5379         kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
5380         spin_unlock(&vcpu->kvm->mmu_lock);
5381 }
5382
5383 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
5384 {
5385         gpa_t gpa;
5386         int r;
5387
5388         if (vcpu->arch.mmu->direct_map)
5389                 return 0;
5390
5391         gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
5392
5393         r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
5394
5395         return r;
5396 }
5397 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
5398
5399 static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
5400 {
5401         LIST_HEAD(invalid_list);
5402
5403         if (likely(kvm_mmu_available_pages(vcpu->kvm) >= KVM_MIN_FREE_MMU_PAGES))
5404                 return 0;
5405
5406         while (kvm_mmu_available_pages(vcpu->kvm) < KVM_REFILL_PAGES) {
5407                 if (!prepare_zap_oldest_mmu_page(vcpu->kvm, &invalid_list))
5408                         break;
5409
5410                 ++vcpu->kvm->stat.mmu_recycled;
5411         }
5412         kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
5413
5414         if (!kvm_mmu_available_pages(vcpu->kvm))
5415                 return -ENOSPC;
5416         return 0;
5417 }
5418
5419 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u64 error_code,
5420                        void *insn, int insn_len)
5421 {
5422         int r, emulation_type = 0;
5423         bool direct = vcpu->arch.mmu->direct_map;
5424
5425         /* With shadow page tables, fault_address contains a GVA or nGPA.  */
5426         if (vcpu->arch.mmu->direct_map) {
5427                 vcpu->arch.gpa_available = true;
5428                 vcpu->arch.gpa_val = cr2;
5429         }
5430
5431         r = RET_PF_INVALID;
5432         if (unlikely(error_code & PFERR_RSVD_MASK)) {
5433                 r = handle_mmio_page_fault(vcpu, cr2, direct);
5434                 if (r == RET_PF_EMULATE)
5435                         goto emulate;
5436         }
5437
5438         if (r == RET_PF_INVALID) {
5439                 r = vcpu->arch.mmu->page_fault(vcpu, cr2,
5440                                                lower_32_bits(error_code),
5441                                                false);
5442                 WARN_ON(r == RET_PF_INVALID);
5443         }
5444
5445         if (r == RET_PF_RETRY)
5446                 return 1;
5447         if (r < 0)
5448                 return r;
5449
5450         /*
5451          * Before emulating the instruction, check if the error code
5452          * was due to a RO violation while translating the guest page.
5453          * This can occur when using nested virtualization with nested
5454          * paging in both guests. If true, we simply unprotect the page
5455          * and resume the guest.
5456          */
5457         if (vcpu->arch.mmu->direct_map &&
5458             (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5459                 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2));
5460                 return 1;
5461         }
5462
5463         /*
5464          * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5465          * optimistically try to just unprotect the page and let the processor
5466          * re-execute the instruction that caused the page fault.  Do not allow
5467          * retrying MMIO emulation, as it's not only pointless but could also
5468          * cause us to enter an infinite loop because the processor will keep
5469          * faulting on the non-existent MMIO address.  Retrying an instruction
5470          * from a nested guest is also pointless and dangerous as we are only
5471          * explicitly shadowing L1's page tables, i.e. unprotecting something
5472          * for L1 isn't going to magically fix whatever issue cause L2 to fail.
5473          */
5474         if (!mmio_info_in_cache(vcpu, cr2, direct) && !is_guest_mode(vcpu))
5475                 emulation_type = EMULTYPE_ALLOW_RETRY;
5476 emulate:
5477         /*
5478          * On AMD platforms, under certain conditions insn_len may be zero on #NPF.
5479          * This can happen if a guest gets a page-fault on data access but the HW
5480          * table walker is not able to read the instruction page (e.g instruction
5481          * page is not present in memory). In those cases we simply restart the
5482          * guest, with the exception of AMD Erratum 1096 which is unrecoverable.
5483          */
5484         if (unlikely(insn && !insn_len)) {
5485                 if (!kvm_x86_ops->need_emulation_on_page_fault(vcpu))
5486                         return 1;
5487         }
5488
5489         return x86_emulate_instruction(vcpu, cr2, emulation_type, insn,
5490                                        insn_len);
5491 }
5492 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5493
5494 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
5495 {
5496         struct kvm_mmu *mmu = vcpu->arch.mmu;
5497         int i;
5498
5499         /* INVLPG on a * non-canonical address is a NOP according to the SDM.  */
5500         if (is_noncanonical_address(gva, vcpu))
5501                 return;
5502
5503         mmu->invlpg(vcpu, gva, mmu->root_hpa);
5504
5505         /*
5506          * INVLPG is required to invalidate any global mappings for the VA,
5507          * irrespective of PCID. Since it would take us roughly similar amount
5508          * of work to determine whether any of the prev_root mappings of the VA
5509          * is marked global, or to just sync it blindly, so we might as well
5510          * just always sync it.
5511          *
5512          * Mappings not reachable via the current cr3 or the prev_roots will be
5513          * synced when switching to that cr3, so nothing needs to be done here
5514          * for them.
5515          */
5516         for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5517                 if (VALID_PAGE(mmu->prev_roots[i].hpa))
5518                         mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5519
5520         kvm_x86_ops->tlb_flush_gva(vcpu, gva);
5521         ++vcpu->stat.invlpg;
5522 }
5523 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5524
5525 void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5526 {
5527         struct kvm_mmu *mmu = vcpu->arch.mmu;
5528         bool tlb_flush = false;
5529         uint i;
5530
5531         if (pcid == kvm_get_active_pcid(vcpu)) {
5532                 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5533                 tlb_flush = true;
5534         }
5535
5536         for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5537                 if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
5538                     pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].cr3)) {
5539                         mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5540                         tlb_flush = true;
5541                 }
5542         }
5543
5544         if (tlb_flush)
5545                 kvm_x86_ops->tlb_flush_gva(vcpu, gva);
5546
5547         ++vcpu->stat.invlpg;
5548
5549         /*
5550          * Mappings not reachable via the current cr3 or the prev_roots will be
5551          * synced when switching to that cr3, so nothing needs to be done here
5552          * for them.
5553          */
5554 }
5555 EXPORT_SYMBOL_GPL(kvm_mmu_invpcid_gva);
5556
5557 void kvm_enable_tdp(void)
5558 {
5559         tdp_enabled = true;
5560 }
5561 EXPORT_SYMBOL_GPL(kvm_enable_tdp);
5562
5563 void kvm_disable_tdp(void)
5564 {
5565         tdp_enabled = false;
5566 }
5567 EXPORT_SYMBOL_GPL(kvm_disable_tdp);
5568
5569
5570 /* The return value indicates if tlb flush on all vcpus is needed. */
5571 typedef bool (*slot_level_handler) (struct kvm *kvm, struct kvm_rmap_head *rmap_head);
5572
5573 /* The caller should hold mmu-lock before calling this function. */
5574 static __always_inline bool
5575 slot_handle_level_range(struct kvm *kvm, struct kvm_memory_slot *memslot,
5576                         slot_level_handler fn, int start_level, int end_level,
5577                         gfn_t start_gfn, gfn_t end_gfn, bool lock_flush_tlb)
5578 {
5579         struct slot_rmap_walk_iterator iterator;
5580         bool flush = false;
5581
5582         for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
5583                         end_gfn, &iterator) {
5584                 if (iterator.rmap)
5585                         flush |= fn(kvm, iterator.rmap);
5586
5587                 if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
5588                         if (flush && lock_flush_tlb) {
5589                                 kvm_flush_remote_tlbs_with_address(kvm,
5590                                                 start_gfn,
5591                                                 iterator.gfn - start_gfn + 1);
5592                                 flush = false;
5593                         }
5594                         cond_resched_lock(&kvm->mmu_lock);
5595                 }
5596         }
5597
5598         if (flush && lock_flush_tlb) {
5599                 kvm_flush_remote_tlbs_with_address(kvm, start_gfn,
5600                                                    end_gfn - start_gfn + 1);
5601                 flush = false;
5602         }
5603
5604         return flush;
5605 }
5606
5607 static __always_inline bool
5608 slot_handle_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5609                   slot_level_handler fn, int start_level, int end_level,
5610                   bool lock_flush_tlb)
5611 {
5612         return slot_handle_level_range(kvm, memslot, fn, start_level,
5613                         end_level, memslot->base_gfn,
5614                         memslot->base_gfn + memslot->npages - 1,
5615                         lock_flush_tlb);
5616 }
5617
5618 static __always_inline bool
5619 slot_handle_all_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5620                       slot_level_handler fn, bool lock_flush_tlb)
5621 {
5622         return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5623                                  PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5624 }
5625
5626 static __always_inline bool
5627 slot_handle_large_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5628                         slot_level_handler fn, bool lock_flush_tlb)
5629 {
5630         return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL + 1,
5631                                  PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5632 }
5633
5634 static __always_inline bool
5635 slot_handle_leaf(struct kvm *kvm, struct kvm_memory_slot *memslot,
5636                  slot_level_handler fn, bool lock_flush_tlb)
5637 {
5638         return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5639                                  PT_PAGE_TABLE_LEVEL, lock_flush_tlb);
5640 }
5641
5642 static void free_mmu_pages(struct kvm_mmu *mmu)
5643 {
5644         free_page((unsigned long)mmu->pae_root);
5645         free_page((unsigned long)mmu->lm_root);
5646 }
5647
5648 static int alloc_mmu_pages(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
5649 {
5650         struct page *page;
5651         int i;
5652
5653         /*
5654          * When using PAE paging, the four PDPTEs are treated as 'root' pages,
5655          * while the PDP table is a per-vCPU construct that's allocated at MMU
5656          * creation.  When emulating 32-bit mode, cr3 is only 32 bits even on
5657          * x86_64.  Therefore we need to allocate the PDP table in the first
5658          * 4GB of memory, which happens to fit the DMA32 zone.  Except for
5659          * SVM's 32-bit NPT support, TDP paging doesn't use PAE paging and can
5660          * skip allocating the PDP table.
5661          */
5662         if (tdp_enabled && kvm_x86_ops->get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
5663                 return 0;
5664
5665         page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
5666         if (!page)
5667                 return -ENOMEM;
5668
5669         mmu->pae_root = page_address(page);
5670         for (i = 0; i < 4; ++i)
5671                 mmu->pae_root[i] = INVALID_PAGE;
5672
5673         return 0;
5674 }
5675
5676 int kvm_mmu_create(struct kvm_vcpu *vcpu)
5677 {
5678         uint i;
5679         int ret;
5680
5681         vcpu->arch.mmu = &vcpu->arch.root_mmu;
5682         vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
5683
5684         vcpu->arch.root_mmu.root_hpa = INVALID_PAGE;
5685         vcpu->arch.root_mmu.root_cr3 = 0;
5686         vcpu->arch.root_mmu.translate_gpa = translate_gpa;
5687         for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5688                 vcpu->arch.root_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5689
5690         vcpu->arch.guest_mmu.root_hpa = INVALID_PAGE;
5691         vcpu->arch.guest_mmu.root_cr3 = 0;
5692         vcpu->arch.guest_mmu.translate_gpa = translate_gpa;
5693         for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5694                 vcpu->arch.guest_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5695
5696         vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
5697
5698         ret = alloc_mmu_pages(vcpu, &vcpu->arch.guest_mmu);
5699         if (ret)
5700                 return ret;
5701
5702         ret = alloc_mmu_pages(vcpu, &vcpu->arch.root_mmu);
5703         if (ret)
5704                 goto fail_allocate_root;
5705
5706         return ret;
5707  fail_allocate_root:
5708         free_mmu_pages(&vcpu->arch.guest_mmu);
5709         return ret;
5710 }
5711
5712 #define BATCH_ZAP_PAGES 10
5713 static void kvm_zap_obsolete_pages(struct kvm *kvm)
5714 {
5715         struct kvm_mmu_page *sp, *node;
5716         int nr_zapped, batch = 0;
5717
5718 restart:
5719         list_for_each_entry_safe_reverse(sp, node,
5720               &kvm->arch.active_mmu_pages, link) {
5721                 /*
5722                  * No obsolete valid page exists before a newly created page
5723                  * since active_mmu_pages is a FIFO list.
5724                  */
5725                 if (!is_obsolete_sp(kvm, sp))
5726                         break;
5727
5728                 /*
5729                  * Skip invalid pages with a non-zero root count, zapping pages
5730                  * with a non-zero root count will never succeed, i.e. the page
5731                  * will get thrown back on active_mmu_pages and we'll get stuck
5732                  * in an infinite loop.
5733                  */
5734                 if (sp->role.invalid && sp->root_count)
5735                         continue;
5736
5737                 /*
5738                  * No need to flush the TLB since we're only zapping shadow
5739                  * pages with an obsolete generation number and all vCPUS have
5740                  * loaded a new root, i.e. the shadow pages being zapped cannot
5741                  * be in active use by the guest.
5742                  */
5743                 if (batch >= BATCH_ZAP_PAGES &&
5744                     cond_resched_lock(&kvm->mmu_lock)) {
5745                         batch = 0;
5746                         goto restart;
5747                 }
5748
5749                 if (__kvm_mmu_prepare_zap_page(kvm, sp,
5750                                 &kvm->arch.zapped_obsolete_pages, &nr_zapped)) {
5751                         batch += nr_zapped;
5752                         goto restart;
5753                 }
5754         }
5755
5756         /*
5757          * Trigger a remote TLB flush before freeing the page tables to ensure
5758          * KVM is not in the middle of a lockless shadow page table walk, which
5759          * may reference the pages.
5760          */
5761         kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
5762 }
5763
5764 /*
5765  * Fast invalidate all shadow pages and use lock-break technique
5766  * to zap obsolete pages.
5767  *
5768  * It's required when memslot is being deleted or VM is being
5769  * destroyed, in these cases, we should ensure that KVM MMU does
5770  * not use any resource of the being-deleted slot or all slots
5771  * after calling the function.
5772  */
5773 static void kvm_mmu_zap_all_fast(struct kvm *kvm)
5774 {
5775         lockdep_assert_held(&kvm->slots_lock);
5776
5777         spin_lock(&kvm->mmu_lock);
5778         trace_kvm_mmu_zap_all_fast(kvm);
5779
5780         /*
5781          * Toggle mmu_valid_gen between '0' and '1'.  Because slots_lock is
5782          * held for the entire duration of zapping obsolete pages, it's
5783          * impossible for there to be multiple invalid generations associated
5784          * with *valid* shadow pages at any given time, i.e. there is exactly
5785          * one valid generation and (at most) one invalid generation.
5786          */
5787         kvm->arch.mmu_valid_gen = kvm->arch.mmu_valid_gen ? 0 : 1;
5788
5789         /*
5790          * Notify all vcpus to reload its shadow page table and flush TLB.
5791          * Then all vcpus will switch to new shadow page table with the new
5792          * mmu_valid_gen.
5793          *
5794          * Note: we need to do this under the protection of mmu_lock,
5795          * otherwise, vcpu would purge shadow page but miss tlb flush.
5796          */
5797         kvm_reload_remote_mmus(kvm);
5798
5799         kvm_zap_obsolete_pages(kvm);
5800         spin_unlock(&kvm->mmu_lock);
5801 }
5802
5803 static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
5804 {
5805         return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
5806 }
5807
5808 static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
5809                         struct kvm_memory_slot *slot,
5810                         struct kvm_page_track_notifier_node *node)
5811 {
5812         kvm_mmu_zap_all_fast(kvm);
5813 }
5814
5815 void kvm_mmu_init_vm(struct kvm *kvm)
5816 {
5817         struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5818
5819         node->track_write = kvm_mmu_pte_write;
5820         node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
5821         kvm_page_track_register_notifier(kvm, node);
5822 }
5823
5824 void kvm_mmu_uninit_vm(struct kvm *kvm)
5825 {
5826         struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5827
5828         kvm_page_track_unregister_notifier(kvm, node);
5829 }
5830
5831 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
5832 {
5833         struct kvm_memslots *slots;
5834         struct kvm_memory_slot *memslot;
5835         int i;
5836
5837         spin_lock(&kvm->mmu_lock);
5838         for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5839                 slots = __kvm_memslots(kvm, i);
5840                 kvm_for_each_memslot(memslot, slots) {
5841                         gfn_t start, end;
5842
5843                         start = max(gfn_start, memslot->base_gfn);
5844                         end = min(gfn_end, memslot->base_gfn + memslot->npages);
5845                         if (start >= end)
5846                                 continue;
5847
5848                         slot_handle_level_range(kvm, memslot, kvm_zap_rmapp,
5849                                                 PT_PAGE_TABLE_LEVEL, PT_MAX_HUGEPAGE_LEVEL,
5850                                                 start, end - 1, true);
5851                 }
5852         }
5853
5854         spin_unlock(&kvm->mmu_lock);
5855 }
5856
5857 static bool slot_rmap_write_protect(struct kvm *kvm,
5858                                     struct kvm_rmap_head *rmap_head)
5859 {
5860         return __rmap_write_protect(kvm, rmap_head, false);
5861 }
5862
5863 void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
5864                                       struct kvm_memory_slot *memslot)
5865 {
5866         bool flush;
5867
5868         spin_lock(&kvm->mmu_lock);
5869         flush = slot_handle_all_level(kvm, memslot, slot_rmap_write_protect,
5870                                       false);
5871         spin_unlock(&kvm->mmu_lock);
5872
5873         /*
5874          * kvm_mmu_slot_remove_write_access() and kvm_vm_ioctl_get_dirty_log()
5875          * which do tlb flush out of mmu-lock should be serialized by
5876          * kvm->slots_lock otherwise tlb flush would be missed.
5877          */
5878         lockdep_assert_held(&kvm->slots_lock);
5879
5880         /*
5881          * We can flush all the TLBs out of the mmu lock without TLB
5882          * corruption since we just change the spte from writable to
5883          * readonly so that we only need to care the case of changing
5884          * spte from present to present (changing the spte from present
5885          * to nonpresent will flush all the TLBs immediately), in other
5886          * words, the only case we care is mmu_spte_update() where we
5887          * have checked SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE
5888          * instead of PT_WRITABLE_MASK, that means it does not depend
5889          * on PT_WRITABLE_MASK anymore.
5890          */
5891         if (flush)
5892                 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5893                         memslot->npages);
5894 }
5895
5896 static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
5897                                          struct kvm_rmap_head *rmap_head)
5898 {
5899         u64 *sptep;
5900         struct rmap_iterator iter;
5901         int need_tlb_flush = 0;
5902         kvm_pfn_t pfn;
5903         struct kvm_mmu_page *sp;
5904
5905 restart:
5906         for_each_rmap_spte(rmap_head, &iter, sptep) {
5907                 sp = page_header(__pa(sptep));
5908                 pfn = spte_to_pfn(*sptep);
5909
5910                 /*
5911                  * We cannot do huge page mapping for indirect shadow pages,
5912                  * which are found on the last rmap (level = 1) when not using
5913                  * tdp; such shadow pages are synced with the page table in
5914                  * the guest, and the guest page table is using 4K page size
5915                  * mapping if the indirect sp has level = 1.
5916                  */
5917                 if (sp->role.direct &&
5918                         !kvm_is_reserved_pfn(pfn) &&
5919                         PageTransCompoundMap(pfn_to_page(pfn))) {
5920                         pte_list_remove(rmap_head, sptep);
5921
5922                         if (kvm_available_flush_tlb_with_range())
5923                                 kvm_flush_remote_tlbs_with_address(kvm, sp->gfn,
5924                                         KVM_PAGES_PER_HPAGE(sp->role.level));
5925                         else
5926                                 need_tlb_flush = 1;
5927
5928                         goto restart;
5929                 }
5930         }
5931
5932         return need_tlb_flush;
5933 }
5934
5935 void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
5936                                    const struct kvm_memory_slot *memslot)
5937 {
5938         /* FIXME: const-ify all uses of struct kvm_memory_slot.  */
5939         spin_lock(&kvm->mmu_lock);
5940         slot_handle_leaf(kvm, (struct kvm_memory_slot *)memslot,
5941                          kvm_mmu_zap_collapsible_spte, true);
5942         spin_unlock(&kvm->mmu_lock);
5943 }
5944
5945 void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
5946                                    struct kvm_memory_slot *memslot)
5947 {
5948         bool flush;
5949
5950         spin_lock(&kvm->mmu_lock);
5951         flush = slot_handle_leaf(kvm, memslot, __rmap_clear_dirty, false);
5952         spin_unlock(&kvm->mmu_lock);
5953
5954         lockdep_assert_held(&kvm->slots_lock);
5955
5956         /*
5957          * It's also safe to flush TLBs out of mmu lock here as currently this
5958          * function is only used for dirty logging, in which case flushing TLB
5959          * out of mmu lock also guarantees no dirty pages will be lost in
5960          * dirty_bitmap.
5961          */
5962         if (flush)
5963                 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5964                                 memslot->npages);
5965 }
5966 EXPORT_SYMBOL_GPL(kvm_mmu_slot_leaf_clear_dirty);
5967
5968 void kvm_mmu_slot_largepage_remove_write_access(struct kvm *kvm,
5969                                         struct kvm_memory_slot *memslot)
5970 {
5971         bool flush;
5972
5973         spin_lock(&kvm->mmu_lock);
5974         flush = slot_handle_large_level(kvm, memslot, slot_rmap_write_protect,
5975                                         false);
5976         spin_unlock(&kvm->mmu_lock);
5977
5978         /* see kvm_mmu_slot_remove_write_access */
5979         lockdep_assert_held(&kvm->slots_lock);
5980
5981         if (flush)
5982                 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5983                                 memslot->npages);
5984 }
5985 EXPORT_SYMBOL_GPL(kvm_mmu_slot_largepage_remove_write_access);
5986
5987 void kvm_mmu_slot_set_dirty(struct kvm *kvm,
5988                             struct kvm_memory_slot *memslot)
5989 {
5990         bool flush;
5991
5992         spin_lock(&kvm->mmu_lock);
5993         flush = slot_handle_all_level(kvm, memslot, __rmap_set_dirty, false);
5994         spin_unlock(&kvm->mmu_lock);
5995
5996         lockdep_assert_held(&kvm->slots_lock);
5997
5998         /* see kvm_mmu_slot_leaf_clear_dirty */
5999         if (flush)
6000                 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
6001                                 memslot->npages);
6002 }
6003 EXPORT_SYMBOL_GPL(kvm_mmu_slot_set_dirty);
6004
6005 void kvm_mmu_zap_all(struct kvm *kvm)
6006 {
6007         struct kvm_mmu_page *sp, *node;
6008         LIST_HEAD(invalid_list);
6009         int ign;
6010
6011         spin_lock(&kvm->mmu_lock);
6012 restart:
6013         list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
6014                 if (sp->role.invalid && sp->root_count)
6015                         continue;
6016                 if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign))
6017                         goto restart;
6018                 if (cond_resched_lock(&kvm->mmu_lock))
6019                         goto restart;
6020         }
6021
6022         kvm_mmu_commit_zap_page(kvm, &invalid_list);
6023         spin_unlock(&kvm->mmu_lock);
6024 }
6025
6026 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
6027 {
6028         WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
6029
6030         gen &= MMIO_SPTE_GEN_MASK;
6031
6032         /*
6033          * Generation numbers are incremented in multiples of the number of
6034          * address spaces in order to provide unique generations across all
6035          * address spaces.  Strip what is effectively the address space
6036          * modifier prior to checking for a wrap of the MMIO generation so
6037          * that a wrap in any address space is detected.
6038          */
6039         gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
6040
6041         /*
6042          * The very rare case: if the MMIO generation number has wrapped,
6043          * zap all shadow pages.
6044          */
6045         if (unlikely(gen == 0)) {
6046                 kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
6047                 kvm_mmu_zap_all_fast(kvm);
6048         }
6049 }
6050
6051 static unsigned long
6052 mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
6053 {
6054         struct kvm *kvm;
6055         int nr_to_scan = sc->nr_to_scan;
6056         unsigned long freed = 0;
6057
6058         mutex_lock(&kvm_lock);
6059
6060         list_for_each_entry(kvm, &vm_list, vm_list) {
6061                 int idx;
6062                 LIST_HEAD(invalid_list);
6063
6064                 /*
6065                  * Never scan more than sc->nr_to_scan VM instances.
6066                  * Will not hit this condition practically since we do not try
6067                  * to shrink more than one VM and it is very unlikely to see
6068                  * !n_used_mmu_pages so many times.
6069                  */
6070                 if (!nr_to_scan--)
6071                         break;
6072                 /*
6073                  * n_used_mmu_pages is accessed without holding kvm->mmu_lock
6074                  * here. We may skip a VM instance errorneosly, but we do not
6075                  * want to shrink a VM that only started to populate its MMU
6076                  * anyway.
6077                  */
6078                 if (!kvm->arch.n_used_mmu_pages &&
6079                     !kvm_has_zapped_obsolete_pages(kvm))
6080                         continue;
6081
6082                 idx = srcu_read_lock(&kvm->srcu);
6083                 spin_lock(&kvm->mmu_lock);
6084
6085                 if (kvm_has_zapped_obsolete_pages(kvm)) {
6086                         kvm_mmu_commit_zap_page(kvm,
6087                               &kvm->arch.zapped_obsolete_pages);
6088                         goto unlock;
6089                 }
6090
6091                 if (prepare_zap_oldest_mmu_page(kvm, &invalid_list))
6092                         freed++;
6093                 kvm_mmu_commit_zap_page(kvm, &invalid_list);
6094
6095 unlock:
6096                 spin_unlock(&kvm->mmu_lock);
6097                 srcu_read_unlock(&kvm->srcu, idx);
6098
6099                 /*
6100                  * unfair on small ones
6101                  * per-vm shrinkers cry out
6102                  * sadness comes quickly
6103                  */
6104                 list_move_tail(&kvm->vm_list, &vm_list);
6105                 break;
6106         }
6107
6108         mutex_unlock(&kvm_lock);
6109         return freed;
6110 }
6111
6112 static unsigned long
6113 mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
6114 {
6115         return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
6116 }
6117
6118 static struct shrinker mmu_shrinker = {
6119         .count_objects = mmu_shrink_count,
6120         .scan_objects = mmu_shrink_scan,
6121         .seeks = DEFAULT_SEEKS * 10,
6122 };
6123
6124 static void mmu_destroy_caches(void)
6125 {
6126         kmem_cache_destroy(pte_list_desc_cache);
6127         kmem_cache_destroy(mmu_page_header_cache);
6128 }
6129
6130 static void kvm_set_mmio_spte_mask(void)
6131 {
6132         u64 mask;
6133
6134         /*
6135          * Set the reserved bits and the present bit of an paging-structure
6136          * entry to generate page fault with PFER.RSV = 1.
6137          */
6138
6139         /*
6140          * Mask the uppermost physical address bit, which would be reserved as
6141          * long as the supported physical address width is less than 52.
6142          */
6143         mask = 1ull << 51;
6144
6145         /* Set the present bit. */
6146         mask |= 1ull;
6147
6148         /*
6149          * If reserved bit is not supported, clear the present bit to disable
6150          * mmio page fault.
6151          */
6152         if (IS_ENABLED(CONFIG_X86_64) && shadow_phys_bits == 52)
6153                 mask &= ~1ull;
6154
6155         kvm_mmu_set_mmio_spte_mask(mask, mask, ACC_WRITE_MASK | ACC_USER_MASK);
6156 }
6157
6158 int kvm_mmu_module_init(void)
6159 {
6160         int ret = -ENOMEM;
6161
6162         /*
6163          * MMU roles use union aliasing which is, generally speaking, an
6164          * undefined behavior. However, we supposedly know how compilers behave
6165          * and the current status quo is unlikely to change. Guardians below are
6166          * supposed to let us know if the assumption becomes false.
6167          */
6168         BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
6169         BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
6170         BUILD_BUG_ON(sizeof(union kvm_mmu_role) != sizeof(u64));
6171
6172         kvm_mmu_reset_all_pte_masks();
6173
6174         kvm_set_mmio_spte_mask();
6175
6176         pte_list_desc_cache = kmem_cache_create("pte_list_desc",
6177                                             sizeof(struct pte_list_desc),
6178                                             0, SLAB_ACCOUNT, NULL);
6179         if (!pte_list_desc_cache)
6180                 goto out;
6181
6182         mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
6183                                                   sizeof(struct kvm_mmu_page),
6184                                                   0, SLAB_ACCOUNT, NULL);
6185         if (!mmu_page_header_cache)
6186                 goto out;
6187
6188         if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
6189                 goto out;
6190
6191         ret = register_shrinker(&mmu_shrinker);
6192         if (ret)
6193                 goto out;
6194
6195         return 0;
6196
6197 out:
6198         mmu_destroy_caches();
6199         return ret;
6200 }
6201
6202 /*
6203  * Calculate mmu pages needed for kvm.
6204  */
6205 unsigned long kvm_mmu_calculate_default_mmu_pages(struct kvm *kvm)
6206 {
6207         unsigned long nr_mmu_pages;
6208         unsigned long nr_pages = 0;
6209         struct kvm_memslots *slots;
6210         struct kvm_memory_slot *memslot;
6211         int i;
6212
6213         for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
6214                 slots = __kvm_memslots(kvm, i);
6215
6216                 kvm_for_each_memslot(memslot, slots)
6217                         nr_pages += memslot->npages;
6218         }
6219
6220         nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
6221         nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
6222
6223         return nr_mmu_pages;
6224 }
6225
6226 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
6227 {
6228         kvm_mmu_unload(vcpu);
6229         free_mmu_pages(&vcpu->arch.root_mmu);
6230         free_mmu_pages(&vcpu->arch.guest_mmu);
6231         mmu_free_memory_caches(vcpu);
6232 }
6233
6234 void kvm_mmu_module_exit(void)
6235 {
6236         mmu_destroy_caches();
6237         percpu_counter_destroy(&kvm_total_used_mmu_pages);
6238         unregister_shrinker(&mmu_shrinker);
6239         mmu_audit_disable();
6240 }